Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIAlertController dismiss completion never gets called

In the following code, when my web view fails to load, the alert is properly shown with the Retry button, as expected. The alert goes away when tapping the Retry button, but the completion never gets called. Why is this?

func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
    let alert = UIAlertController(title: "Network Error", message: "There was a error loading the page.", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Retry", style: .default, handler: { _ in
        alert.dismiss(animated: true, completion: {
            self.webView.loadHTMLString("Reloaded", baseURL: nil)
        })
    }));

    self.present(alert, animated: true, completion: nil)
}
like image 885
Jeff Wolski Avatar asked Mar 23 '26 08:03

Jeff Wolski


1 Answers

Don't call alert.dismiss inside the alert action. The alert controller will automatically be dismissed when the user taps one of the alert buttons.

You just need:

alert.addAction(UIAlertAction(title: "Retry", style: .default, handler: { _ in
    self.webView.loadHTMLString("Reloaded", baseURL: nil)
}))
like image 166
rmaddy Avatar answered Mar 24 '26 21:03

rmaddy