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.
Is it common practice to remove Auth.auth().addStateDidChangeListener once auth is found for a session?
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("