Reputation: 1601
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
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.
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)
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