ios - 蜂窝数据的可达性测试

标签 ios swift swift3 reachability

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

    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

    }
}

我需要更改它,以便它也可以为蜂窝返回 true,我看到人们使用 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()
    }
    `

最佳答案

swift 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

关于ios - 蜂窝数据的可达性测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43951648/

相关文章:

ios - UICollectionViewCell 仅在逐步调试时显示

ios - Swift 3 中的 Microsoft Azure 远程通知

ios - 如何使 UITextField 的行为类似于 swift 3 中的银行输入格式?

ios - 将图像上传到 Firebase 存储

ios - 单击按钮编辑 UITextView

ios - 无法从 UIImagePickerController 获取图像

ios - 在 iOS 中连接 AWS IoT 代理

arrays - 字典中的多个参数

swift - Swift 中判断字符串是否只包含不可见字符

swift - 有没有一些方法可以检查类是否是从泛型类型继承的?