最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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(" 

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论