Value of type 'AuthDataResult' has no member ‘uid’

孤街浪徒 提交于 2019-12-18 07:14:42

问题


I am trying to access a user's uid in Firebase Authentication. I created a createUser completion block in my code and at the end of the block I want to check for the user in which I named firUser. When I try to add firUser.uid in my User I get the error message

"Value of type 'AuthDataResult' has no member ‘uid’"

Below is a copy of the code I wrote hopefully some one can help me.

Auth.auth().createUser(withEmail: email, password: password, completion: { (firUser, error) in
  if error != nil {
     // report error
  } else if let firUser = firUser {
    let newUser = User(uid: firUser.uid, username: username, fullName: fullName, bio: "", website: "", follows: [], followedBy: [], profileImage: self.profileImage)
    newUser.save(completion: { (error) in
      if error != nil {
        // report
      } else {
        // Login User
        Auth.auth().signIn(withEmail: email, password: password, completion: { (firUser, error) in
          if let error = error {
           // report error
           print(error)
         } else {
           self.dismiss(animated: true, completion: nil)
         }
        })
      }
    })
  }
})

回答1:


According to the guide, when using .createUser,

If the new account was successfully created, the user is signed in, and you can get the user's account data from the result object that's passed to the callback method.

Notice in the sample, you get back authResult, not a User object. authResult contains some information, including the User. You can get to the User using authResult.user.

In addition, when calling the method, if successful, the user is already signed in, so there's no reason to sign them in again. I changed the parameter name to authResult from the sample to help eliminate some of the confusion.

Auth.auth().createUser(withEmail: email, password: password, completion: { authResult, error in
  if let error = error {
     // report error
     return
  } 
  guard let authResult = authResult else { return }
  let firUser = authResult.user
  let newUser = User(uid: firUser.uid, username: username, fullName: fullName, bio: "", website: "", follows: [], followedBy: [], profileImage: self.profileImage)
  newUser.save(completion: { (error) in
    if let error = error {
      // report
    } else {
      // not sure what you need to do here anymore since the user is already signed in
    }
  })
})


来源:https://stackoverflow.com/questions/51409307/value-of-type-authdataresult-has-no-member-uid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!