gpt4 book ai didi

ios - 互联网重新连接 swift

转载 作者:可可西里 更新时间:2023-11-01 01:09:02 27 4
gpt4 key购买 nike

如果没有互联网连接,我的应用目前会显示警报。但是,我希望它在检测到互联网连接后自动重新连接,而无需用户重新启动应用程序。

我目前使用的代码是

if Reachability.isConnectedToNetwork() == true {
print("Internet Connection Available!")
} else {
let alertController = UIAlertController(title: "Alert",
message: "Internet Connection not Available!",
preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}

谁能给点建议?如果我的问题不清楚,请告诉我。谢谢大家!

最佳答案

你应该在 applicationDidFinishLaunching 方法中添加 Reachability 的观察者,如下所示,

NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChanged(_:)), name: NSNotification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil)
Reach().monitorReachabilityChanges()

同样实现这个方法,

@objc func networkStatusChanged(_ notification: Notification) {
let userInfo = (notification as NSNotification).userInfo
if let status = userInfo?["Status"] as? String, status == "Offline" {
//Display alert view
} else if let status = userInfo?["Status"] as? String, status != "Unknown" {
//Internet connection is active
}
}

当有事件的互联网连接时,上述功能会自动触发调用。

关于ios - 互联网重新连接 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49811581/

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