ios - UIAlert 在 iOS Swift 中显示两次?
问题描述
我一直在尝试显示 Internet 连接是否可用的警报。实现了检查互联网的代码,它工作正常。但是,当互联网不可读时,我试图显示警报但警报显示两次。
这是尝试的代码:
@objc func reachabilityChanged(_ note: NSNotification) {
let reachability = note.object as! Reachability
if reachability.connection != .unavailable {
if reachability.connection == .wifi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
} else {
print("Not reachable")
let alert = UIAlertController(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// self.window?.rootViewController?.present(alert, animated: true, completion: nil)
topMostViewController().present(alert, animated: true, completion: nil)
// let alertVC = UIAlertController(title: "No Internet Connection" , message: "Make sure your device is connected to the internet.", preferredStyle: UIAlertController.Style.alert)
// let okAction = UIAlertAction(title: "Okay", style: UIAlertAction.Style.cancel) { (alert) in
//// exit(0) // Your code here
// }
// alertVC.addAction(okAction)
// DispatchQueue.main.async {
// var presentVC = self.window?.rootViewController
// while let next = presentVC?.presentedViewController {
// presentVC = next
// }
// presentVC?.present(alertVC, animated: true, completion: nil)
// }
}
}
func topMostViewController() -> UIViewController {
var topViewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController
while ((topViewController?.presentedViewController) != nil) {
topViewController = topViewController?.presentedViewController
}
return topViewController!
}
解决方案
推荐阅读
- android - 在 Android 应用程序中将 Locale 更改为 ARABIC 时出现问题
- corda - 请注册实体“net.corda.finance.schemas.CashSchemaV1”
- python - setuptools 中的 install_requires 是否可以在某些软件包没有明确的 yocto-recipe 的情况下工作
- angular - 只有在有效值之后,如何在 Rx 订阅中做某事?
- android - 使用多个关键字搜索数据库的 sqlite 查询
- linux - CronTab 每 5 分钟重启一次不起作用
- c# - 通知所有消费者消息
- android - 平板电脑容器android中的片段显示问题
- css - 在一个组件中修复 mat-fab 按钮
- c# - 从 db RESTful Web API 最佳实践中传递日期