gpt4 book ai didi

ios - 互联网连接状态快速可达性

转载 作者:搜寻专家 更新时间:2023-11-01 07:02:05 25 4
gpt4 key购买 nike

我有以下代码来确定是否有互联网连接。此代码工作正常。我怎么知道我是否突然失去联系

  var reachability:Reachability?
reachability = Reachability()
self.reachability = Reachability.init()
if((self.reachability!.connection) != .none)
{
print("Internet available")
}

可达性类是否具有报告连接断开的功能。如果无法通过可达性来处理该问题,还有什么其他选择

最佳答案

在 AppDelegate/Vc 中声明它

let reachability = Reachability()!

NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}

//

当状态改变时调用这个方法

@objc func reachabilityChanged(note: Notification) {

let reachability = note.object as! Reachability

switch reachability.connection {
case .wifi:
print("Reachable via WiFi")
case .cellular:
print("Reachable via Cellular")
case .none:
print("Network not reachable")
}
}

//

为了避免崩溃不要忘记取消注册

reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)

关于ios - 互联网连接状态快速可达性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50571045/

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