I am writing a function that checks whether a users device is connected to the internet. If it is not it warns the users with an Alert box.
Initially I was using the following below which worked perfectly:
var data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) as NSData?
But this has been deprecated in iOS 9.
So I changed my code to the following.
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork()->Bool{
var Status:Bool = false
let url = NSURL(string: "https://google.com/")
var response: NSURLResponse?
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, err -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
Status = true
}
}
})
task.resume()
return Status
}}
The issue is that it always says that there is NO Internet connection which is obviously wrong. Which means the "Bool" is always false. What am I doing wrong?
Thanks in advance.
Using reachability or some other test is how you should meet your actual requirement.
However, to answer your question, the reason that this always returns false
is that the data task is asynchronous - that is it will complete independently of the function call, so by the time it completes and tries to set status to true
, the function has already returned false