Apple 已弃用
SCNetworkReachabilityCreateWithAddress
,虽然文档没有说明 SCNetworkReachabilityGetFlags
也已弃用,但看起来两者都即将被淘汰。苹果没有建议继任者,所以我的问题是,达到类似结果以测试可达性的好方法是什么?这是我使用的代码:
var currentReachabilityStatus: ReachabilityStatus {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return .notReachable
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return .notReachable
}
...
我当前的代码可以工作,但该功能即将停用。
推荐使用Network的NWPathMonitor 方法说明
示例:
import Network
class Reachability {
let monitor = NWPathMonitor()
let queue = DispatchQueue.global(qos: .background)
init() {
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
// network reachable
} else {
// network not reachable
}
}
monitor.start(queue: queue)
}
}