1

I have a login screen that raises an alert when login fails. The code that calls the alert is run from a callback closure which itself calls a function in the main VC.

        _ = UserProfile.logIn(emailAddressLabel.text!, passwordLabel.text!) { success in
            if success {
                self.performSegue(withIdentifier: "mainTabBarSegue", sender: nil)
            }
            else {
                self.displayFailedLoginAlert()
            }

            self.loggingIn = false
        }

and the displayFailedLoginAlert looks like this:

func displayFailedLoginAlert () {
    let alert = UIAlertController(title: "Login", message: "Login Failed", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: { _ in
        alert.dismiss(animated: false, completion: nil)
    }))
    self.present(alert, animated: false, completion: nil)
}

However, when I do this I get:

Warning: Attempt to present <UIAlertController: 0x7ff8fd0b5800>  on <LoginViewController: 0x7ff8fcc0deb0> which is already presenting <UIAlertController: 0x7ff8fe0cca00>

I have tried a number of different approaches and either get this or a crash if I use a UIAlertController as a class member. What am I doing wrong, I just can't see it?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • And you're sure your callback isn't called twice? What does the logIn method look like? – Frizzo Jan 05 '18 at 14:30
  • 1
    You're clearly presenting alert view controller in a situation where you're already showing one. I'd suggest adding breakpoints everywhere you instantiate a `UIAlertController` and identify how this is happening. – Rob Jan 05 '18 at 14:45
  • Frizzo, you're right, on the second login attempt, the callback is called twice. I'll need to find out why tomorrow. Should have checked this first. Thanks for hint – Brian Parkes Jan 05 '18 at 23:08

2 Answers2

1

You don't need to tell the alert to dismiss at all. The default behavior when tapping an action in a UIAlertController is that the alert will dismiss. Just pass nil to the handler.

Connor Neville
  • 7,291
  • 4
  • 28
  • 44
  • This is true, but almost certainly unrelated to the OPs question. The problem is likely occurring when the alert is presented, not when it is dismissed. – Rob Jan 05 '18 at 14:47
0

The issue was that, each time the user logged in I added an observer to the API call. So, on the second login attempt the closure was called twice and so raised the error. Thanks to Frizzo for pointing me in the right direction