Jam*_*esG 1 swift uialertcontroller
我的ViewController中有一个快速if语句,用于检查Internet连接是否可用.如果没问题,但是当互联网未连接时,我收到此错误:
尝试显示其视图不在窗口层次结构中!
我以前有UIAlertView,但Xcode告诉我它已被弃用,所以我需要将它更改为UIAlertController.执行此操作后,这是发生错误的时间.
这是If语句:
let alert = UIAlertController(title: "This can't be true", message:"This app needs internet, but you don't have it, please connect", preferredStyle: .Alert)
override func viewDidLoad() {
super.viewDidLoad()
// Check for internet Connection
if Reachability.isConnectedToNetwork() == true {
print("Internet connection OK")
} else {
print("Internet connection FAILED")
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
好的,快速而又脏的方式,不确定这是否正确,Stack Overflow请评论并帮助进一步讨论.
你的项目正在创建一个带有透明UIViewController的UIWindow,然后在其上呈现UIAlertController.但是视图尚未完成加载,因此无法找到它.
(我想)
把它放在你的viewDidLoad()中:
if Reachability.isConnectedToNetwork() == true {
print("Internet connection OK")
// do something
}
Run Code Online (Sandbox Code Playgroud)
然后,将其写出viewDidLoad()的范围:
override func viewDidAppear(animated: Bool) {
if Reachability.isConnectedToNetwork() == false {
print("Internet connection FAILED")
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
}
Run Code Online (Sandbox Code Playgroud)
不推荐用于有大量要加载的视图,因为警报可能需要一段时间才能显示.
如果有效,请告诉我,让我知道您的解决方案.
| 归档时间: |
|
| 查看次数: |
1410 次 |
| 最近记录: |