Why did Auth.auth().currentUser?.uid return a nil value?

Justin Reddick

I want to store users under their Firebase generated uid. When I attempt to use this code:

  func showCredentials() {
        let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
        Auth.auth().signInAndRetrieveData(with: credential) { (AuthDataResult, error) in
            if error != nil {
                print("Something went wrong with our Facebook User: ", error)
                return
            }
            print("Successfuly logged in with our Facebook User: ", AuthDataResult)
            self.performSegue(withIdentifier: "FacebookSegue", sender: self)
        }
        FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start {
            (connection, graphResult, error) in
            if error != nil {
                print("Failed to Start Graph Request:", error)
                return
            }
            print(graphResult)
            let facebookDetail = graphResult as! NSDictionary
            let userID = facebookDetail["id"]
            let fullName = facebookDetail["name"]
            let email = facebookDetail["email"]
            let providerName = "Facebook"
            let userValues = (["Email": email, "Full Name": fullName, "UID": userID, "Provider":providerName])
            let databaseRef = Database.database().reference()
            let key = databaseRef.child("node").childByAutoId().key ?? ""
            let childUpdates = ["/Users/\(userID))/": userValues]
            databaseRef.updateChildValues(childUpdates)
            print(userID!)
            print(fullName!)
            let firebaseID = Auth.auth().currentUser?.uid
            print(firebaseID!)
        }
    }

The error I am given is: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value on the line where I am attempting to print the firebaseID. Why is the value of Auth.auth().currentUser?.uid nil and what can I do to obtain this value?

Sh_Khan

You init 2 asynchronous requests at the same time

Auth.auth().signInAndRetrieveData and FBSDKGraphRequest(graphPath: "/me"

where the second may finish first causing the crash as the auth isn't yet finished , so you need to nest them to be sure that you access the user after the auth signin finishes

func showCredentials() {
    let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
    Auth.auth().signInAndRetrieveData(with: credential) { (AuthDataResult, error) in
        if error != nil {
            print("Something went wrong with our Facebook User: ", error)
            return
        }
        FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start {
        (connection, graphResult, error) in
        if error != nil {
            print("Failed to Start Graph Request:", error)
            return
        }
        print(graphResult)
        let facebookDetail = graphResult as! NSDictionary
        let userID = facebookDetail["id"]
        let fullName = facebookDetail["name"]
        let email = facebookDetail["email"]
        let providerName = "Facebook"
        let userValues = (["Email": email, "Full Name": fullName, "UID": userID, "Provider":providerName])
        let databaseRef = Database.database().reference()
        let key = databaseRef.child("node").childByAutoId().key ?? ""
        let childUpdates = ["/Users/\(userID))/": userValues]
        databaseRef.updateChildValues(childUpdates)
        print(userID!)
        print(fullName!)
        let firebaseID = Auth.auth().currentUser?.uid
        print(firebaseID!)

        DispatchQueue.main.async {
         print("Successfuly logged in with our Facebook User: ", AuthDataResult)
         self.performSegue(withIdentifier: "FacebookSegue", sender: self)
        }

    }


    }

}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Firebase -Auth.auth().currentUser?.phoneNumber returns nil

Why does firebase.auth().currentUser return NULL even when the user is logged in

Ember-auth currentUser

React-Native-Firebase Spread auth().currentUser Object {...auth().currentUser}

firebase.auth().currentUser is null

auth.currentUser.updateProfile is not a function

Firebase Auth: Edit UID

Laravel auth::attempt return true but auth::check() false why?

Trying to list user favourities from API, getting "TypeError: null is not an object (evaluating 'firebase.auth().currentUser.uid')

Why Laravel Auth::check always return false?

auth.onAuthStateChanged not triggering after auth.currentUser.updateProfile in Firebase

Get firebase.auth().currentUser with async/await

auth().currentUser.reload() returns undefined

useEffect not updating on auth.currentUser change

firebase auth.currentUser.email error/bug?

How to async/await on firebase.auth().currentUser?

{Closed} Firebase.auth.currentUser is never null

Firebase.auth.currentUser is never null

Firebase auth.currentUser error using typescript

What does $uid and auth.uid stand for?

What will be there in request.auth.uid?

Does firebase auth UID expires or not?

firebase uid always return nil

Laravel Auth return to index

Why I insert implementation 'com.google.firebase:firebase-admin:6.13.0' into gradle, then Firebase.auth.currentUser become invalid?

Auth::attempt always return false and I don't know why

Which firebase value from firebase-auth to use as uid in my own database?

Firebase Firestore Securitty Rule | Allow read if field value same as auth uid

Firestore Invalid Permissions: request.auth.uid in