UIAlert错误,其视图不在窗口层次结构中 [英] UIAlert error, whose view is not in the window hierarchy
问题描述
我正在建立网络连接,
我将检查可达性代码放在viewDidLoad中,以便在没有网络的情况下通过提醒用户来通知用户。
I put checking reachability code in viewDidLoad, so that I notify User by alerting if there is not network.
这是我的代码,
class ViewController: UIViewController {
var reachability : Reachability?
override func viewDidLoad() {
super.viewDidLoad()
if reachability?.isReachable() == true
{
print("reachable")
}else{
let myAlert = UIAlertController(title: "No network", message:
"Your network is not working", preferredStyle:
UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style:
UIAlertActionStyle.Default, handler: nil)
myAlert.addAction(okAction)
self.presentViewController(myAlert, animated: true, completion:
nil)
}
但是如果我尝试使用模拟器或手机,
会显示错误消息
but If I try on my simulator or cellphone, it shows error message that
2015-11-08 16: 43:52.173 PracticeReachability [5494:2661290]警告:尝试呈现其视图不在窗口层次结构中的视图!
2015-11-08 16:43:52.173 PracticeReachability[5494:2661290] Warning: Attempt to present on whose view is not in the window hierarchy!
我尝试放置
var myAlert = UIAlertController()
和
var myAlert:UIAlertController!
and var myAlert :UIAlertController!
两者都不起作用。
问题 >
我的其他Alerts在同一ViewController中可以正常工作。
为什么只有这种方法不起作用?
My other Alerts work fine in same ViewController. Why only this is not working?
又如何使它起作用?
推荐答案
我认为viewDidLoad中尚未将视图控制器的视图添加到屏幕中。尝试将代码移至viewDidAppear。
I don't think the view controller's view has been added to the screen yet in viewDidLoad. Try moving your code to viewDidAppear.
这篇关于UIAlert错误,其视图不在窗口层次结构中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!