Search code examples
iosswiftuialertcontrollerdismissuialertaction

How to Dismiss Presenting View Controller when "Ok" Action Tapped in UIAlertController


I'm trying to dismiss the current view controller in the completion handler of a UIAlertAction, but it is not dismissing. I have written the following code (The loading indicator is simply a loading alert controller that I dismiss when the data was successfully uploaded):

loadingIndicator.dismiss(animated: true) {                           
      let success = UIAlertController(title: "Successfully Uploaded", message: "", preferredStyle: .alert)
      let ok = UIAlertAction(title: "Ok", style: .default, handler: { _ in
               print("Ok selected") //this is working correctly
               self.dismiss(animated: true, completion: nil) //this is not
      })
                      
      success.addAction(ok)
      self.present(success, animated: true, completion: nil)
}

However, after clicking on "Ok" in the alert, "Ok selected" is printed but the view controller is not dismissed. Nothing else shows up in the debugger.


Solution

  • Try dismissing it on Main thread and also check if ViewController is presented or pushed in navigation hierarchy.

    loadingIndicator.dismiss(animated: true) {
        let success = UIAlertController(title: "Successfully Uploaded", message: "", preferredStyle: .alert)
        let ok = UIAlertAction(title: "Ok", style: .default, handler: { _ in
            DispatchQueue.main.async {
                self.dismiss(animated: true, completion: nil)
                 // If pushed use PopViewController on navigation
                 // self.navigationController?.popViewController(animated: true)
            }
        })
        success.addAction(ok)
        self.present(success, animated: true, completion: nil)
    }
    

    To check if ViewController is being presented or not use self.isBeingPresented property.