加载UIAlertController时出错

时间:2015-09-27 16:32:02

标签: swift2 ios9 uialertcontroller

我想在互联网连接不可用时加载提醒。检查互联网连接的功能已准备就绪,但我无法加载警报。所以我只是在没有任何条件等的情况下将警报代码放在viewDidLoad中并且出现了这个错误:

  

警告:尝试在x.ViewController:0x127646f00上显示UIAlertController:0x12752d400,其视图不在窗口层次结构中!

代码:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // Delegates
        verificationCode.delegate = self

        let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
        let action = UIAlertAction(title: "OK", style: .Default) { _ in }
        alert.addAction(action)
        self.presentViewController(alert, animated: true) {}


        if (!Util.isConnectedToNetwork()) {
            self.isConnected = false
        }
    }

你能告诉我如何解决它吗?

3 个答案:

答案 0 :(得分:1)

错误告诉你出了什么问题。

您正在尝试在viewDidLoad中显示视图控制器,但视图虽然已加载,但不在任何层次结构中。尝试将代码放在viewDidAppear方法中,该方法在视图出现在屏幕上后调用,并且位于视图层次结构中。

答案 1 :(得分:1)

我认为这可以帮助您解决问题:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // Delegates
    verificationCode.delegate = self

    let alert: UIAlertController = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)

    //Create and add the Cancel action
    let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
        //Just dismiss the action sheet
    }
    alert.addAction(cancelAction)

    //Create and add first option action
    let action: UIAlertAction = UIAlertAction(title: "OK", style: .Default) { action -> Void in
        //Code for action here
    }
    alert.addAction(delete)

    alert.popoverPresentationController?.sourceView = sender as UIView
    UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alert, animated: true, completion: nil)


    if (!Util.isConnectedToNetwork()) {
        self.isConnected = false
    }
}

答案 2 :(得分:0)

将代码从viewDidLoad

移至viewDidAppear
override func viewDidAppear(animated: Bool) {
    // Delegates
    verificationCode.delegate = self

    let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
    let action = UIAlertAction(title: "OK", style: .Default) { _ in }
    alert.addAction(action)
    self.presentViewController(alert, animated: true) {}


    if (!Util.isConnectedToNetwork()) {
        self.isConnected = false
    }


}