0

I need a method to check if a server is online. Ideally it will just return either true/false.

I have tried this:

    class func serverIsOnline() -> Bool{
        let session = NSURLSession.sharedSession()
        let urlString = "http://myserver.com"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 3.0)

        let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

            if let httpResponse = response as? NSHTTPURLResponse {
                if httpResponse.statusCode == 200 {
                    //server online
                    return true
                } else {
                    //server offline
                    return false
                }
            }
        }
        dataTask.resume()
    }

When I try to return true/false I get the following error:

Unexpected non-void return value in void function

How can I amend this function so that I can check if my server is online and return true/false ?

Daniel Storm
  • 15,870
  • 6
  • 74
  • 133
KML
  • 2,162
  • 5
  • 21
  • 45

2 Answers2

1

The problem with your method is

  1. It's asynchrous
  2. Your closure can't return anything, it's Void.

To fix it, you'll have to make the call synchronous as well as store the response in a Bool so that you can return it once the closure completes. Make dataTaskWithRequestHandler synchrounous, like this. Declare a variable on the top like reachable and set it to true or false inside the closure, then return it after the task completes.

Community
  • 1
  • 1
saagarjha
  • 2,058
  • 1
  • 15
  • 34
  • 1
    A completion handler would also be a good way to get this data back. – saagarjha May 09 '16 at 18:10
  • It seems like a major effort to make is synchronous, is it necessary ? – KML May 09 '16 at 18:13
  • The thing with network requests is that they can complete at any time in the future. How you'd like to handle that is basically up to you...do you want to wait for the data to arrive? Then you'll have to make it synchronous like I've mentioned above. If you'd simply like run some code once it's completed, a completion handler is the way to go, as the above duplicate shows. – saagarjha May 09 '16 at 18:19
0

How about taking a handler in the parameter and calling it with the appropriate value,

class func serverIsOnline(isOnline: (Bool) -> Void) -> Void {

        let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

            if let httpResponse = response as? NSHTTPURLResponse {
                isOnline(httpResponse.statusCode == 200)
            }
        }

        dataTask.resume()
    }
SirH
  • 445
  • 2
  • 6