ios - Swift: UIAlertController inside while loop -


struggling following code:

 var connected = false     while !connected {         let msg = "press cancel"         let alert = uialertcontroller(title: "test", message: msg, preferredstyle: .alert)         let action = uialertaction(title: "cancel", style: .default) { (action:uialertaction) in             connected = true         }         alert.addaction(action)         print ("hello")         present(alert, animated: true, completion: nil)      } 
  1. the uialertcontroller never shown, "hello" printed on , on again
  2. if insert "connected = true" after while clause uialertcontroller shown, i'm not able show again changing action "connected = false"

what doing wrong?

first of all, mentioned in comments, not idea present alert controller continuously in while loop. believe intended functionality display alert whenever connected variable becomes false.

to accomplish use notificationcenter respond follows:

in viewdidload:

notificationcenter.default.addobserver(self, selector: #selector(viewcontroller.displayalert), name: nsnotification.name(rawvalue: "connectiondropped"), object: nil) 

add willset property observer connected:

var connected: bool! {   willset {     if newvalue == false && oldvalue != false {       notificationcenter.default.post(name: nsnotification.name(rawvalue: "connectiondropped"), object: nil)     }   } } 

then whenever set self.connected = false, run method:

@objc func displayalert() {   let msg = "press cancel"   let alert = uialertcontroller(title: "test", message: msg, preferredstyle: .alert)   let action = uialertaction(title: "cancel", style: .default) { (action:uialertaction) in     self.connected = true   }   alert.addaction(action)   print ("hello")   present(alert, animated: true, completion: nil) } 

just make sure set connected after view hierarchy has been loaded e.g in viewdidappear.

once you're done view can remove observer:

deinit {   notificationcenter.default.removeobserver(self, name: nsnotification.name(rawvalue: "connectiondropped"), object: nil) } 

edit:

the functionality need provided reachability framework, in particular reachabilitychanged notification. can call displayalert using similar approach outlined above; documented on readme document.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -