检查是否有可用的互联网连接。
检查是否有可用的互联网连接。
我正在编写一个函数,检查用户的设备是否连接到互联网。如果没有连接,它会通过一个弹窗警告用户。\n最初我使用了下面的代码,这个代码完美地工作:\nvar data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) as NSData?\n
\n但这在iOS 9中已经被弃用。\n所以我将我的代码改成了下面的样子。\nimport Foundation\nimport SystemConfiguration\npublic class Reachability {\nclass func isConnectedToNetwork()->Bool{\n var Status:Bool = false\n let url = NSURL(string: \"https://google.com/\")\n var response: NSURLResponse?\n let request = NSMutableURLRequest(URL: url!)\n request.HTTPMethod = \"HEAD\"\n request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData\n request.timeoutInterval = 10.0\n let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()\n let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)\n let task = session.dataTaskWithRequest(request, completionHandler: {data, response, err -> Void in\n if let httpResponse = response as? NSHTTPURLResponse {\n if httpResponse.statusCode == 200 {\n Status = true\n }\n } \n })\n task.resume()\n return Status\n}}\n
\n问题是它总是说没有互联网连接,显然是错误的。这意味着\"Bool\"始终为false。我做错了什么?\n提前感谢。