简体   繁体   中英

UIAlert error, whose view is not in the window hierarchy

I am working on my network connectivity,

I put checking reachability code in viewDidLoad, so that I notify User by alerting if there is not network.

Here is my code for this,

class ViewController: UIViewController {
var reachability : Reachability?

override func viewDidLoad() {
    super.viewDidLoad()
    if reachability?.isReachable() == true
     {
         print("reachable")
     }else{

        let myAlert = UIAlertController(title: "No network", message:
            "Your network is not working", preferredStyle:
            UIAlertControllerStyle.Alert)
        let okAction = UIAlertAction(title: "Ok", style:
            UIAlertActionStyle.Default, handler: nil)
        myAlert.addAction(okAction)
        self.presentViewController(myAlert, animated: true, completion:
            nil)

    }

but If I try on my simulator or cellphone, it shows error message that

2015-11-08 16:43:52.173 PracticeReachability[5494:2661290] Warning: Attempt to present on whose view is not in the window hierarchy!

I tried put

var myAlert = UIAlertController()

and var myAlert :UIAlertController!

both doesn't make it work.

Question

My other Alerts work fine in same ViewController. Why only this is not working?

And How can I make it work?

I don't think the view controller's view has been added to the screen yet in viewDidLoad. Try moving your code to viewDidAppear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM