简体   繁体   中英

Firebase uid returning nil after authentication (Swift)

In my app, as soon as it opens I check to see if the user is already authenticated in the viewdidload of the initial view. If they are already authenticated, I perform a segue to the main view. I'm even printing the uid to the log at this time and it's printing correctly.

override func viewDidLoad() {
    super.viewDidLoad()


    if ref.authData != nil {
        let uid = ref.authData.uid
        print(uid)

I then do the same later in the app to get some of the user's info when they click on their profile settings. I write the exact same code to fetch their uid, but this time the uid is returning nil and is crashing with the error

"fatal error: unexpectedly found nil while unwrapping an Optional value"

Is this a firebase or simulator issue?

Edit : This issue has only occurred twice. Otherwise, the code itself works as intended, which makes me wonder whether it is a firebase or simulator issue.

You want to use the observeAuthEventWithBlock method, which is a realtime authentication listener.

override func viewDidAppear() {
  let ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com")

  ref.observeAuthEventWithBlock({ authData in
    if authData != nil {
        // user authenticated
        print(authData)
        self.performSegueWithIdentifier("LoginToOtherView", sender: nil)
    } else {
        // No user is signed in
    }
  })
}

About the exact error you are encountering I am not sure, but a Swift-yer way of doing your code (and avoiding your error) would be to call:

if let uid = ref.authData.uid {
    print(uid)
}

This code safely unwraps both authData and the UID.

I was having this problem and it took me hours. Then I realized that I'd just forgotten to do this:

ref = FIRDatabase.database().reference()

before

var ref: FIRDatabaseReference!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM