DeiForm
DeiForm

Reputation: 664

Error when loading UIAlertController

I want to load an alert when internet connection is not available. The function for checking internet connection is ready but I cannot load the alert. So I just put the alert code in viewDidLoad without any conditions etc. and got this error:

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

Code:

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

Could you tell me how to fix it?

Upvotes: 0

Views: 330

Answers (3)

Matthew Usdin
Matthew Usdin

Reputation: 1284

Swift 4 Update I think this could help you for your problem :

override func viewDidLoad() {
    super.viewDidLoad()

    verificationCode.delegate = self

    let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .alert)
    let delete = UIAlertAction(title: "OK", style: .default) { (_) in }
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
    alert.addAction(cancelAction)
    alert.addAction(delete)

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

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

Upvotes: 1

bluemobi
bluemobi

Reputation: 31

Move the code to viewDidAppear from 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
    }


}

Upvotes: 0

Abizern
Abizern

Reputation: 150565

The error tells you what has gone wrong.

You are trying to present a view controller in viewDidLoad except the view, although loaded, is not in any hierarchy. Try putting the code in the viewDidAppear method, which is called after the view appears on screen, and is in a view hierarchy.

Upvotes: 1

Related Questions