present UIAlertController while a presentation is in progress

Viewed 3307

I'm trying to display two different alerts immediately after each other. The first one is a loading indicator. The second one is an alert that tell the user if what they were doing has succeeded or not following a UDP message. I have simplified the code for presentation purposes.

My problem is that although I'm dismissing the loadingAlert before I call my second alert I still get an error:

Warning: Attempt to present UIAlertController on ViewController while a presentation is in progress!

My second alert is never shown.

Here is my Swift 4 code:

func getUpdate()
{    
    let loading = alert(title: "Performing Task...")

    DispatchQueue.global(qos: .userInitiated).async {
        let server:UDPServer=UDPServer(address:"0.0.0.0", port:5006)
        let (data,_,_) = server.recv(1024)

        DispatchQueue.main.async
        {
            loading.dismiss(animated: false, completion: nil)

            OperationQueue.main.addOperation
            {
                alert(title: "How can I show this alert?")
            }
        }
    }
}

func alert(title:String) -> UIAlertController
{
    let alertController = UIAlertController(title: title, message: "", preferredStyle: UIAlertControllerStyle.alert)
    ...
    rootViewController?.present(alertController, animated: true, completion: nil)

    return alertController
}

What would be the best way of doing this?

1 Answers

Make use of the completion parameter in the call to dismiss:

DispatchQueue.main.async{
    loading.dismiss(animated: false) {
        OperationQueue.main.addOperation {
            alert(title: "How can I show this alert?")
        }
    }
}
Related