细胞数据的可达性测试

时间:2017-05-13 09:47:19

标签: ios swift swift3 reachability

我目前正在使用下面的类来检查互联网连接,但是当用户进行蜂窝数据连接时它不会返回

    import Foundation
   import SystemConfiguration

public class Reachability {

    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(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }

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

        let isReachable = flags == .reachable
        let needsConnection = flags == .connectionRequired

        return isReachable && !needsConnection

    }
}

我需要更改它以便它也可以返回真实的细胞,我看到人们使用git的Reachability类但我通过我的应用程序使用它所以我需要改变这个类但我不要知道我怎么能这样做

,用法如下:`

 if Reachability.isConnectedToNetwork() == true {
    print("Internet connection OK")

 JSONParseFunction()

} else {
        print("Internet connection FAILED")
        let alert = UIAlertView(title: "You are not connected to internet ", message: "make sure you are connected to internet ", delegate: nil, cancelButtonTitle: "چشم")
        alert.show()
    }
    `

1 个答案:

答案 0 :(得分:0)

斯威夫特3: 您提供的代码仅适用于wifi可用的情况,如果是蜂窝数据,则无法使用。

只需更改下面提到的代码行,即

// Only Working for WIFI

let isReachable = flags == .reachable
let needsConnection = flags == .connectionRequired
return isReachable && !needsConnection

使用下面提到的代码,即

// Working for both WIFI and Cellular

//kSCNetworkFlagsReachable: The specified node name or address can be reached using the current network configuration.

let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let retVal = (isReachable && !needsConnection)
return retVal