gpt4 book ai didi

ios - 使用 Swift 检查 ios 中蜂窝网络的互联网连接

转载 作者:搜寻专家 更新时间:2023-11-01 06:18:33 26 4
gpt4 key购买 nike

我使用了堆栈溢出的解决方案来检查互联网连接它适用于 wifi 网络但不适用于蜂窝网络

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

var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)

guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {
return false
}

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

let isReachable = flags.contains(.Reachable)
let needsConnection = flags.contains(.ConnectionRequired)
return (isReachable && !needsConnection)
}

}

如何检查蜂窝网络的 Internet 连接?

我在尝试 Rock 的解决方案时遇到此错误

enter image description here

最佳答案

尝试使用这个第三方库: Reachability

并编写这段代码:

let reachability = Reachability.reachabilityForInternetConnection()

reachability?.whenReachable = { reachability in
// keep in mind this is called on a background thread
// and if you are updating the UI it needs to happen
// on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
if reachability.isReachableViaWiFi() {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
}
reachability?.whenUnreachable = { reachability in
// keep in mind this is called on a background thread
// and if you are updating the UI it needs to happen
// on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
print("Not reachable")
}
}

reachability?.startNotifier()

关于ios - 使用 Swift 检查 ios 中蜂窝网络的互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38950267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com