Mariah Mariah - 2 months ago 20
iOS Question

How to prevent viewing a view when clicking on a button (Swift)

I'm having a button on view that contains this condition:

FIRAuth.auth()?.addStateDidChangeListener { auth, user in
if let user = user {
self.performSegue(withIdentifier: "AddDevice", sender: nil)
}
else {
let alert = UIAlertController(title: "Sorry", message:"You Have to register", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default) { _ in })
self.present(alert, animated: true){}
}
}


To check whether the user is logged in or not!
If logged in the segue should run and open the next view

If not an alert should appear to the user.

But the next view contains a function that retrieved the current user data! (Logged in user) in viewDidLoad function!

So when the user not logged in and I click to this button I keep getting crash instead of the alert!

How can I prevent viewing the next view and just present the alert!
So I can avoid the crash?

Answer

From your description is sounds like the segue is always executing, but it's not what you want.

Connect the segue from the view controller itself, name it and put the whole method inside IBAction connected to the button.

Something like this:

@IBAction func loginDidTouch(sender: AnyObject) {
    FIRAuth.auth()?.addStateDidChangeListener { auth, user in
        if let user = user {
            self.performSegue(withIdentifier: "AddDevice", sender: nil)
         }
         else {
         let alert = UIAlertController(title: "Sorry", message:"You Have to register", preferredStyle: .alert)
         alert.addAction(UIAlertAction(title: "Ok", style: .default) { _ in })
         self.present(alert, animated: true){}
    }

}

screenshots will come soon