First of all, as mentioned in the comments, its not a good idea to present your alert controller continuously in a while loop. I believe your intended functionality is to display an alert whenever the connected
variable becomes false.
To accomplish this use NotificationCenter
to respond as follows:
In viewDidLoad
:
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.displayAlert), name: NSNotification.Name(rawValue: "connectionDropped"), object: nil)
Add a willSet
property observer to connected
:
var connected: Bool! {
willSet {
if newValue == false && oldValue != false {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "connectionDropped"), object: nil)
}
}
}
Then whenever you set self.connected = false
, you will run this 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 you set connected after the view hierarchy has been loaded e.g in viewDidAppear
.
Once you're done with the view you can then remove the observer:
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "connectionDropped"), object: nil)
}
EDIT:
The functionality you need is provided with the Reachability framework, in particular with the reachabilityChanged
notification. You can then call the displayAlert
using a similar approach that I outlined above; this is documented on their README document.