Andrej Andrej - 4 months ago 21
iOS Question

How to programatically dismiss UIAlertController without any buttons?

I'm presenting an UIAlertViewController without any buttons, as it is supposed to just inform users that uploading is in progress. The app is supposed to upload some files to Amazon S3 (some things happen on parallel threads) and I'm afraid that the reference to the alert view controller gets lost when I want to dismiss it.

Any idea on what could be wrong?
I even don't know how to debug this since there's no error in the Debug area?

I have a class level property:

var uploadInProgressAlert = UIAlertController()


I use this code to present my alert without buttons (it works):

self.uploadInProgressAlert = UIAlertController(title: "Uploading", message: "Please wait.", preferredStyle: .Alert)
self.presentViewController(self.uploadInProgressAlert, animated: true, completion: nil)


This code is to dismiss the alert (the alert doesn't get dismissed):
self.uploadInProgressAlert.dismissViewControllerAnimated(false, completion: nil)


In this thread: iOS dismiss UIAlertController in response to event someone talked about "holding the reference". I don't know what it means "hold the reference" and I think this could be the root of the problem.

EDIT: I've put the above code in a simple test app and there it works. But when things get complicated with some parallel threads I can't find a way to dismiss the alert.

var delay4s = NSTimer()
var delay8s = NSTimer()
var alert = UIAlertController()

func showAlert() {
if NSClassFromString("UIAlertController") != nil {
alert = UIAlertController(title: "Uploading", message: "Please wait! \n\n", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: nil)
}
}

func dismissAlert(){
self.alert.dismissViewControllerAnimated(true, completion: nil)
}

override func viewDidLoad() {
super.viewDidLoad()
delay4s = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: "showAlert", userInfo: nil, repeats: false)
delay8s = NSTimer.scheduledTimerWithTimeInterval(8.0, target: self, selector: "dismissAlert", userInfo: nil, repeats: false)
}

Answer

I'm not entirely sure if this applies to swift, because I'm an Objective-C programmer, but generally the parent view controller is responsible for dismissing the modally presented view controller (your popup). In Objective-C you would do something like this in the parent view controller:

[self dismissViewControllerAnimated:YES completion:nil];