类型“ AuthDataResult”的值没有成员“ uid”

时间:2018-07-18 19:03:30

标签: swift firebase firebase-authentication

我正在尝试在Firebase身份验证中访问用户的uid。我在代码中创建了一个createUser完成块,在该块的结尾,我想检查我命名为firUser的用户。当我尝试在用户中添加firUser.uid时,出现错误消息

  

“类型为'AuthDataResult'的值没有成员'uid'”

下面是我编写的代码的副本,希望有人可以帮助我。

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 个答案:

答案 0 :(得分:5)

根据guide,在使用.createUser时,

  

如果成功创建了新帐户,则表明用户已登录,   您可以从结果对象中获取用户的帐户数据   传递给回调方法。

在示例中,请注意,您返回authResult,而不是User对象。 authResult包含一些信息,包括用户。您可以使用authResult.user来联系用户。

此外,在调用方法时,如果成功,则用户已经登录,因此没有理由再次登录。我将示例中的参数名称更改为authResult,以消除某些混淆。

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
    }
  })
})