简体   繁体   English

身份验证后Firebase uid返回nil(Swift)

[英]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. 在我的应用程序中,一旦打开,我就会检查用户是否已经在初始视图的viewdidload中通过了身份验证。 If they are already authenticated, I perform a segue to the main view. 如果它们已经通过身份验证,我将对主视图执行segue。 I'm even printing the uid to the log at this time and it's printing correctly. 我什至在此时将uid打印到日志中,并且打印正确。

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 我编写了完全相同的代码以获取其uid,但是这次uid返回nil并因错误而崩溃

"fatal error: unexpectedly found nil while unwrapping an Optional value" “致命错误:解开可选值时意外发现nil”

Is this a firebase or simulator issue? 这是firebase或模拟器问题吗?

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. 否则,代码本身将按预期工作,这使我想知道这是Firebase还是模拟器问题。

You want to use the observeAuthEventWithBlock method, which is a realtime authentication listener. 您想使用observeAuthEventWithBlock方法,它是一个实时身份验证侦听器。

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: 关于您遇到的确切错误,我不确定,但是使用Swift-yer编写代码(并避免出现错误)的方法是调用:

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

This code safely unwraps both authData and the UID. 此代码可以安全地解包authData和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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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