2015-09-27 89 views
0

我想在互聯網連接不可用時加載警報。檢查互聯網連接的功能已準備就緒,但無法加載警報。所以我只是把viewDidLoad中,報警代碼不附加任何條件等,並得到這個錯誤:加載UIAlertController時出錯

Warning: Attempt to present UIAlertController: 0x12752d400 on x.ViewController: 0x127646f00 whose view is not in the window hierarchy!

代碼:

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 
     } 
    } 

你能告訴我如何解決它?

回答

1

該錯誤告訴您出了什麼問題。

您正試圖在viewDidLoad中呈現視圖控制器,但該視圖雖然已加載,但不在任何層次結構中。嘗試將代碼放在viewDidAppear方法中,該方法在屏幕上顯示視圖後調用,並且位於視圖層次結構中。

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 
    } 
} 
0

移動從viewDidLoad中

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 
    } 


} 
代碼viewDidAppear