如何在Swift 3或Swift 4中检查网络连接?

3

我尝试在Swift 3中检查网络连接,但是代码对我没有起作用。

 class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
      SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: UInt32(0))
    if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
      return false
    }

    let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

    return (isReachable && !needsConnection) ? true : false
  }

我也已经导入了SystemConfiguration框架。请建议如何检查。

1
定义“不工作”。 - rmaddy
您可以查看此链接以供参考。它包含了在连接或断开连接时进行网络检查的内容。 http://stackoverflow.com/questions/40066530/my-reachability-notifier-is-only-able-to-be-called-once/40068225#40068225 - Rajan Maheshwari
3个回答

1

最新的swift3代码

检查互联网连接最简单的方法是使用iOS可达性API。请查看下面的链接并下载添加可达性文件到您的项目中。您必须添加系统配置框架到项目中。

 [1]: https://github.com/ashleymills/Reachability.swift/tree/feature/ios10

完成上述工作后,只需编写以下代码以检查网络连接。这里我还编写了一些警告消息。
    func networkStatusChanged(_ notification: Notification) {
    let userInfo = (notification as NSNotification).userInfo
    print(userInfo!)
}
func interNetChecking( )   {
    let status = Reach().connectionStatus()


    switch status {
    case .unknown, .offline:

        let alert = UIAlertController(title: "Check", message: "Internet Connection is Required at first time running the app to load images and videos ", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))

        DispatchQueue.main.async(execute: {
            self.present(alert, animated: true, completion: nil)
        })


        print("Not connected")
    case .online(.wwan):
        print("Connected via WWAN")
    case .online(.wiFi):
        print("Connected via WiFi")
    }


}

0

在Alamofire的情况下

import Alamofire

// 在viewDidLoad()或者AppDelegate中添加如下代码

let reachabilityManager = NetworkReachabilityManager()
    reachabilityManager.listener = { status in

        switch status {

        case .notReachable:
            print("The network is not reachable")
            self.onInternetDisconnection()

        case .unknown :
            print("It is unknown whether the network is reachable")
            self.onInternetDisconnection() // not sure what to do for this case

        case .reachable(.ethernetOrWiFi):
            print("The network is reachable over the WiFi connection")
            self.onInternetConnection()

        case .reachable(.wwan):
            print("The network is reachable over the WWAN connection")
            self.onInternetConnection()

        }
    }

不要忘记调用 reachabilityManager.startListening(),否则监听器将不会被调用。这是一个有趣的链接,因为在模拟器中使用此代码时需要考虑一些事情:https://github.com/Alamofire/Alamofire/issues/2275 - mxlhz

0
   func isConnectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }
    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
}

problemstucks.com


3
如果你连接了Wi-Fi但无法连接到互联网(打开谷歌页面),仍然返回可达性为真。 这是错误的。 - Arildo Junior

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接