Blog

Fixing the Firebase currentUser error in iOS Swift

Published 1 min read

https://firebase.google.com/docs/auth/ios/manage-users?hl=ko#swift_1

Manage Users in Firebase | Firebase Authentication

According to the official docs, there are 2 ways to get the user's info.

if Auth.auth().currentUser != nil { // User is signed in. // ... } else { // No user is signed in. // ... }
Auth.auth().addStateDidChangeListener { auth, user in }

Let's find out why the first way causes an error.

Say you call Auth.auth().currentUser on the thread you're working on, and the main thread also does the job of loading the user's info.

Then there's an inefficiency: you can't do anything else while the user's info is loading.

So that job gets handed off to another thread, and there's a chance the comparison starts before the user info has been received.

But in a case like this, the next tasks have to start only after the user's info has been fully loaded.

So if you use a function with a completionHandler, i.e. the second way of getting the info from earlier, the error can be solved.

Note: currentUser may be null because the auth object hasn't finished initializing. If you use a listener to track the user's sign-in state, you don't need to handle this situation.

The official docs give the solution too.

But there's also a way to stick with the first method,

if Auth.auth().currentUser == nil { DispatchQueue.main.async { // task } }

By handing the task off to the main thread asynchronously, you create a slight delay so the user's info gets loaded in the meantime, it seems, but..

Is it really worth it??

If anything is wrong, please point it out

Comments

Leaving a comment stores your nickname (or GitHub profile info). Privacy policy

GitHub