I\'ve implement Firebase Authorization to login on my iOS app via Facebook and Google. I\'m coding Swift. When the app starts up I need to check whether a user is already si
I've implemented it like this:
FIRAuth.auth()?.addStateDidChangeListener { auth, user in
if let user = user {
// User is signed in. Show home screen
} else {
// No User is signed in. Show user the login screen
}
}
If you don't need the User object after checking, you can replace if let user = user
with a boolean test, like this:
FIRAuth.auth()?.addStateDidChangeListener { auth, user in
if user != nil {
// User is signed in. Show home screen
} else {
// No User is signed in. Show user the login screen
}
}
Where to put the listener (from the comments):
For the cases I used to check if a user is signed in, it was enough to put it at the beginning of viewDidLoad
in the specific view controller. But if you have any cases where you need to check every time you enter the specific view controller then it would be better to put it at the beginning of viewDidAppear
. But I think in most cases you need to check only once, if the user enters the view
If you're setting up the StateDidChangeListener
in application:didFinishLaunchingWithOptions
, you'll notice that it fires once when the listener is attached (to set the initial state, which is nil
when initialising) and then again once it's finished initialising (potentially not nil
). This is intended behaviour, but really impractical if you're setting it up early.
An alternative to using the listener is using NotificationCenter
. This will fire once initialisation has finished:
NotificationCenter.default.addObserver(forName: NSNotification.Name.AuthStateDidChange, object: Auth.auth(), queue: nil) { _ in
let user = Auth.auth().currentUser
}