UIAlert 错误,其视图不在 window 层次结构中

UIAlert error, whose view is not in the window hierarchy

我正在处理我的网络连接,

我把检查可达性的代码放在viewDidLoad中,这样我就可以在没有网络的时候通过警告来通知用户。

这是我的代码,

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)

    }

但如果我在我的模拟器或手机上尝试, 它显示错误消息

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!

两者都不行。

问题

我的其他警报在相同 ViewController 中工作正常。 为什么只有这个不起作用?

我怎样才能让它发挥作用?

我认为视图控制器的视图尚未在 viewDidLoad 中添加到屏幕上。尝试将您的代码移动到 viewDidAppear。