问题
very new to ios development and Firebase.
I have implemented a standard run-of-the-mill ui flow where the app opens to a splash-screen, where it's checked whether user is signed in or not and depending on the state the user is redirected to the login screen or home screen. I'm trying to get a user id from auth listener, and some of my getUserId calls from the userManager are happening before the firebase auth gives a non-nil user id, and the user always ends up going to the registration screen. Would love to know what are the best practices for implementing fetching user id with listeners. Here's some code to support what I'm doing
class UserManager {
static let shared = UserManager()
private var currentUserId: String?
private init() {
print("init initiated")
_ = Auth.auth().addStateDidChangeListener { (auth, user) in
if let user = user {
// User is signed in
print("user id is: \(user.uid)")
self.currentUserId = user.uid
print("current user id loaded: \(self.currentUserId)")
}
}
}
func getCurrentUserId() -> String?{
print("returning user id: \(currentUserId)")
return currentUserId
}
The print output from the console looks something like below: (The user request starts before the firebase listener state changes to non-nil value
nit initiated
returning user id: nil
nil
user id is: c0wTlE5EXaao3aO0rH9J6GKvuM43
current user id loaded: Optional("c0wTlE5EXaao3aO0rH9J6GKvuM43")
I have tried initializing the UserManager directly from AppDelegate, hoping that by the time the rest of the app starts the singleton instance of usermanager would have been successful in obtaining the latest state. But it doesn't work that way apparently.
回答1:
Why don't you try this with a closure completion handler?
Something like this:
Inside UserManager
declare:
var authDidChange: ((String) -> Void)?
Inside addStateDidChangeListener
completion:
authDidChange?(user.uid)
So when you use your UserManager
you will get the auth updates like this:
UserManager.shared.authDidChange = { userId in
print("The obtained user id is: ", userId)
}
来源:https://stackoverflow.com/questions/60517419/right-way-to-implement-firebase-auth-with-state-listener-swift-5