iOS 8可达性始终在模拟器

时间:2016-04-23 19:30:05

标签: ios swift

我正在尝试检测手机是否可以访问互联网。我堆栈溢出它,每次我使用库(https://github.com/ashleymills/Reachability.swift)或我use recomended class methods它只适用于iOS 9.0,但iOS 8它只返回false(至少在模拟器中,我不知道在真正的电话)。有什么想法吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

有同样的问题。对于我的生活,我无法弄清楚原因,所以必须实现这个适用于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
}

显然,如果谷歌贬值 - 解决方法也是如此。但我承担了这种风险:)

根据回答:https://stackoverflow.com/a/29050673/2941553