问题
On initial load, firebase tells me, if user is logged in by firing event like this:
firebase.auth().onAuthStateChanged(func...)
I want to check, if firebase is still checking it. Like show spinner when page loads, wait for firebase to check user and then show app or login/register form, considering user found or not.
Now I just have to show page, then init firebase, and later, if firebase founds user, redirect to app.
回答1:
The listener passed to onAuthStateChanged
will be called with an argument that is either null
or the User
instance.
So it's safe to assume that Firebase is checking the authentication status between your calling of initializeApp
and the listener for onAuthStateChanged
being called. Display the spinner when you call initializeApp
and hide it when the listener is called.
回答2:
Swift 4
Method 1
Check if the automatic creation time of the user is equal to the last sign in time (Which will be the first sign in time if it is indeed their first sign in)
//Current user metadata reference
let newUserRref = Auth.auth().currentUser?.metadata
/*Check if the automatic creation time of the user is equal to the last
sign in time (Which will be the first sign in time if it is indeed
their first sign in)*/
if newUserRref?.creationDate?.timeIntervalSince1970 == newUserRref?.lastSignInDate?.timeIntervalSince1970{
//user is new user
print("Hello new user")
}
else{
//user is returning user
print("Welcome back!")
}
Method 2
ALTERNATIVELY, you can set a global var in App Delegate. Most apps I've worked on use automatic Firebase login if the user already exists; meaning that it will not update the lastSignInDate value and thus still show the user as a new user.
So start by creating a variable in AppDelegate above the class like so:
var newUser = false
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{
Then whenever you call your function to create a new Firebase user, set newUser to true:
newUser = true
Lastly, make an if statement that filters which user your main controller is receiving:
Override func viewDidLoad() {
super.viewDidLoad()
if newUser == true{
print("welcome new user")
showOnboarding()
}
else{
print("Welcome back!")
}
}
Now anytime an existing user logs in, the variable will remain false
来源:https://stackoverflow.com/questions/41883490/is-firebase-checking-for-user-first-time