检查Swift中的网络状态

Ján*_*nos 16 swift

如何检查Swift中的网络状态?在Objective-C Reachability.h .m文件可用.现在怎么办?如何查看我是在线还是离线?

Ash*_*lls 14

如果您正在寻找Swift实现Apple的Reachability类,您可以看一下:

http://github.com/ashleymills/Reachability.swift

这是一个使用通知闭包的课程.

  • http://github.com/ashleymills/Reachability.swift现在支持CocoaPod (3认同)

Con*_*nor 11

你仍然可以在Swift中使用Reachability.洛根对如何Objective-C的文件添加到桥接报一个很好的答案在这里.设置桥接标头后,可以从Swift代码中调用Reachability方法.像这样的东西会起作用:

class func hasConnectivity() -> Bool {
    let reachability: Reachability = Reachability.reachabilityForInternetConnection()
    let networkStatus: Int = reachability.currentReachabilityStatus().value
    return networkStatus != 0
}
Run Code Online (Sandbox Code Playgroud)

  • @connor请注意,Reachability基础例程都是异步的,所以只需立即查询currentReachabilityStatus就没用了.一般来说,你可以使用桥接头来桥接可达性是正确的,一旦完成,任何可达性教程将使用适当的翻译. (3认同)
  • 最好不要与`0`比较,而不是'NotReachable.value`.将来更容易阅读. (3认同)

Ish*_*ngu 7

我会给出最好的解决方案,希望它有所帮助.

import Foundation
import SystemConfiguration

public class Reachability {
    class func isConnectedToNetwork()->Bool{

        var Status:Bool = false
        let url = NSURL(string: "http://google.com/")
        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "HEAD"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 10.0

        var response: NSURLResponse?

        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?

        if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode == 200 {
                Status = true
            }

        }
        else
        {

            let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
            alert.show()
        }

        return Status
    }
}
Run Code Online (Sandbox Code Playgroud)

如何访问或调用其他类:

 if Reachability.isConnectedToNetwork() == true {

// write your code

}
Run Code Online (Sandbox Code Playgroud)