Mariah Mariah - 2 months ago 13
Swift Question

Adding Condition to a Button (Swift)

I want to add a condition to a button.

So if the condition is true another view will be opened through a segue!

Otherwise, nothing happens and an alert will appear to the user.

The two views are linked by a navigational controller.

@IBAction func AddButton(_ sender: AnyObject) {

if FIRAuth.auth()?.currentUser != nil {
self.performSegue(withIdentifier: "AddDevice", sender: nil)

}
else {

let alert = UIAlertController(title: "Sorry", message:"You have to Register First", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default) { _ in })
self.present(alert, animated: true){}
}

}


Here's what I have tried! But it did not give the result I want.

Do2 Do2
Answer

Try this!

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