matthewdossantos matthewdossantos - 4 months ago 18
iOS Question

Change view when clicking alert button not working

Good day,

This is my code:

@IBAction func logOutAction(sender: AnyObject) {

try! FIRAuth.auth()!.signOut()
let alertController = UIAlertController(title: "Sure?", message: "Are you sure you want to log out?", preferredStyle: .Alert)

let defaultAction = UIAlertAction(title: "Yes", style: .Default, handler: nil)
alertController.addAction(defaultAction)

let defaultAction2 = UIAlertAction(title: "No", style: .Cancel, handler: nil)
alertController.addAction(defaultAction2)

self.presentViewController(alertController, animated: true, completion: nil)

let VC = self.storyboard?.instantiateViewControllerWithIdentifier("loginscreen") as! ViewController //The file that controls the view

self.presentViewController(VC, animated: true, completion: nil)


}


As you can see I want to log out the user when pressing the logout button. When the user clicks logout a UIalert popsup asking if they are sure they want to log out, but when I click okay it doesn't switch back to the loginscree ViewController.

Can anyone help me?

Answer

If the last two lines represent the view that you want to present, then you have to execute this code inside the handler of the "Yes" button action:

let defaultAction = UIAlertAction(title: "Yes", style: .Default, handler: { _ in
    let VC = self.storyboard?.instantiateViewControllerWithIdentifier("loginscreen") as! ViewController //The file that controls the view

    self.presentViewController(VC, animated: true, completion: nil)
})

alertController.addAction(defaultAction)
Comments