我在Firebase上遇到问题,尝试用uid
获取Auth.auth().currentUser?.uid
变量似乎返回nil。
我在函数周围放置了各种打印语句(我在下面发布了完整功能),以查看它们是否被调用-如果我在if let user = user
中放置打印语句,则不会被调用。如果我注释掉if let user = user
(及其右括号),则成功调用了print语句,因此我猜user
为nil。
现在,如果将打印内容放置在guard let uid = Auth.auth().currentUser?.uid else {return}
之后,则不会再次调用print语句,这使我相信uid
为nil并且该保护声明正在返回。
我不确定为什么user
和Auth.auth().currentUser?.uid
都为零。如何更改它以成功获取我的uid
变量?
这是提供某些上下文的完整功能:
@IBAction func emailSignupNextPressed(_ sender: Any) {
// Make sure text fields aren't empty
guard nameField.text != "", emailField.text != "", passwordField.text != "", confirmPasswordField.text != "" else {return}
if passwordField.text == confirmPasswordField.text {
Auth.auth().createUser(withEmail: emailField.text!, password: passwordField.text!, completion: { (user, error) in
if let error = error {
print(error.localizedDescription)
}
if let user = user {
guard let uid = Auth.auth().currentUser?.uid else {return}
// Use name as Firebase display name for readability
let changeRequest = Auth.auth().currentUser!.createProfileChangeRequest()
changeRequest.displayName = self.nameField.text!
changeRequest.commitChanges(completion: nil)
// Create child node from userStorage "users". Profile image set to user's unique ID
let imageRef = self.userStorage.child("\(uid).jpg")
let data = UIImageJPEGRepresentation(self.selectProfileImageView.image!, 0.5)
// Upload image to Firebase
let uploadTask = imageRef.putData(data!, metadata: nil, completion: { (metadata, err) in
if err != nil {
print(err!.localizedDescription)
}
imageRef.downloadURL(completion: { (url, er) in
if er != nil {
print(er?.localizedDescription as Any)
}
if let url = url {
emailUserPicString = url.absoluteString
print("\n\n\npic:\(emailUserPicString)\n\n\n")
if emailUserPicString == "" {
let alertController = UIAlertController(title: "Profile Picture Error", message: "Don't forget to choose a profile picture!", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {(alert :UIAlertAction!) in
})
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
return
} else {
self.performSegue(withIdentifier: "emailToSetup", sender: nil)
}
}
})
})
uploadTask.resume()
}
})
} else {
print("Passwords don't match")
passwordAlert()
}
}
最佳答案
auth().currentUser
仅在用户登录时才会返回user
。
您刚刚创建了此用户,因此尚未登录。
通常,您可以从传递到块中的uid
中获取user
,例如:
let uid = user.uid
如果
user
为null,则帐户创建失败,您应该检查该错误。我注意到你在用print(error.localizedDescription)
但您可能要使用:
print(error)
如果错误没有本地化描述。
通常,错误要么表示网络问题,要么表明用户已经拥有一个帐户。
顺便说一句,如果您想登录用户,可以使用
Auth.auth().signIn(withEmail: email, password: password) { … }
关于ios - Firebase-用户和currentUser在闭包内为零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53873999/