Does Firebase Auth State Change Listener Need to be Removed once Auth Found? (Mobile iOSAndroid App) - Stack Overflow

For my iOS app, I implemented Auth.auth().addStateDidChangeListener to get the latest user credentials,

For my iOS app, I implemented Auth.auth().addStateDidChangeListener to get the latest user credentials, and if none is found then sign in automatically anonymously so the user can connect to the database. My intent is to allow anonymous users, and if they want then there is an email/password to link the account. I noticed with the Auth.auth().addStateDidChangeListener always observes the auth state, sometimes the state comes back NIL (during app use, after auth is already found on launch) and with my code, a new anon user is created. This seems almost random. With thousands of user's this is becoming a nuisance.

  1. Is it common practice to remove Auth.auth().addStateDidChangeListener once auth is found for a session?

  2. If so, then what happens when the user is lost (as the listener is telling me it is)? I have seen this on my own device once or twice, during a session after auth was previously found, but cannot recreate it purposefully. The app is heavily used, and it seems to be a fairly rare occurrence but is creating havoc.

My suspicion is this is due to the auth token refresh not being quite seamless, and the state is lost momentarily so my code creates a new user in the meantime.

class For_AuthChange {
    static let shared = For_AuthChange()
    private init () {}
    private var handle: AuthStateDidChangeListenerHandle? //this one is an Auth Listener, NOT a database handle. <<<<<
         
    
    func StackOverFlow_StopObserver_forAuthState() {
        if let handle = handle {
            Auth.auth().removeStateDidChangeListener(handle)
        }
        handle = nil
    }
    
    func StackOverFlow_forAuthState_GetOnAppLaunch() {
        guard handle == nil else { return } // Ensure observer is only set once
        handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
            if let user = user {
                if user.isAnonymous == true {
                    print(" 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744637788a4585250.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信