-1

I am new at this and can not seem to figure out how to use NSURLSession dataTaskWithResult:completion handler replacing NSURLConnection.sendSynchronusRequest(request as URLRequest, returning: &response in the following code. The latter has been depreciated.

public class Reachability {
    class func isConnectedToNetwork() -> Bool {
        var status:Bool = false

        let url = NSURL(string: "https://google.com")
        let request = NSMutableURLRequest(url: url! as URL)
        request.httpMethod = "HEAD"
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 10.0

        var response:URLResponse?

        do {
            let _ = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning: &response) as NSData?
        }
        catch let error as NSError {
            print(error.localizedDescription)
        }

        if let httpResponse = response as? HTTPURLResponse {
            if httpResponse.statusCode == 200 {
                status = true
            }
        }
        return status
    }
}
Crowman
  • 25,242
  • 5
  • 48
  • 56
Garageshop
  • 101
  • 9

1 Answers1

3

Simple solution with a completion handler

class func isConnectedToNetwork(completion: @escaping (Bool) -> ()) {
    let url = URL(string: "https://google.com")!
    var request = URLRequest(url: url)
    request.httpMethod = "HEAD"
    request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
    request.timeoutInterval = 10.0

    URLSession.shared.dataTask(with:request) { (data, response, error) in
      if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
        completion(true)
      } else {
        completion(false)
      }
    }.resume()
}

And to call

Reachability.isConnectedToNetwork { success in
  if success {
    // google is up
  } else {
    // google is down.
  }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • This is FABULOUS. Thanks you so much. – Garageshop Oct 21 '16 at 23:31
  • Now, I can't figure out how to make the call. This is what I have: if Reachability.isConnectedToNetwork() { self.gettingInfo = self.model.getInfo() } else { //Get local questions from the qizz model self.questions = self.model.getLocalQuestions() } – Garageshop Oct 21 '16 at 23:33
  • The method works asynchronously. The result is returned **in** the closure. I updated the answer. – vadian Oct 22 '16 at 04:11