JamesG
JamesG

Reputation: 1601

Attempt to present <UIAlertController: 0x7d92f000> on <test.ViewController: 0x7c87a990> whose view is not in the window hierarchy

I have a quick if statement in my ViewController that checks if the internet connection is available. If yes fine, but when the internet is not connected I get this error:

Attempt to present on whose view is not in the window hierarchy!

I used to have UIAlertView but Xcode told me it was deprecated so I need to change it to UIAlertController. After doing this, this is when the error occurred.

Here is the If statement:

let alert = UIAlertController(title: "This can't be true", message:"This app needs internet, but you don't have it, please connect", preferredStyle: .Alert)

override func viewDidLoad() {
    super.viewDidLoad()

    // Check for internet Connection
    if Reachability.isConnectedToNetwork() == true {
        print("Internet connection OK")
    } else {
        print("Internet connection FAILED")


        alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
        self.presentViewController(alert, animated: true){}
    }
}

Can someone help?

Upvotes: 1

Views: 1996

Answers (1)

MarkP
MarkP

Reputation: 2566

Ok, so a quick and dirty way, Not sure if this is the right way and Stack Overflow please comment and help further this discussion.

Reason

your project is creating a UIWindow with a transparent UIViewController and then presenting the UIAlertController on it. However the view has not finished loading yet so it can't find it.

(I think :S)

Solution

Put this in your viewDidLoad():

if Reachability.isConnectedToNetwork() == true {
    print("Internet connection OK")
    // do something
}

then, write this out of the scope of your viewDidLoad():

override func viewDidAppear(animated: Bool) {
    if Reachability.isConnectedToNetwork() == false {
        print("Internet connection FAILED")
        alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
        self.presentViewController(alert, animated: true){}
    }
}

Not recommended for a view that has a lot to load as the alert might take a while to display.

Let me know if this works, and SO let me know your solutions.

Upvotes: 6

Related Questions