我正在尝试检测手机是否可以访问互联网。我堆栈溢出了它,每次我使用库( https://github.com/ashleymills/Reachability.swift )或我 use recomended class methods 时它只适用于 iOS 9.0,但 iOS 8 它只是返回 false(至少在模拟器中,我不知道在真正的手机中)。有什么想法吗?
最佳答案
遇到同样的问题。对于我的一生,我无法找出原因,因此必须实现这段适用于 iOS 9 和 iOS 8 的解决方法代码:
class func isConnectedToNetwork()-> Bool {
var isConnected:Bool = false
let request = NSMutableURLRequest(URL: NSURL(string: "http://google.com/")!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
var response: NSURLResponse?
do {
try _ = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) as NSData?
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
isConnected = true
}
}
}
catch {
print(error)
}
return isConnected
}
显然,如果 Google 失败了,那么解决方法也会失败。但我冒了这个风险:)
关于iOS 8 可达性在模拟器中总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36815435/