我在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,并且guard语句正在返回。
我不确定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()
}
}
答案 0 :(得分:0)
auth().currentUser
仅在用户登录后才会返回user
。
您刚刚创建了此用户,因此尚未登录。
通常可以从传递到块中的uid
中获取user
,例如:
let uid = user.uid
如果user
为空,则帐户创建失败,您应该检查该错误。我注意到您正在使用
print(error.localizedDescription)
但您可能要使用:
print(error)
以防错误没有本地化描述。
通常,错误要么表示网络问题,要么表明用户已经拥有帐户。
顺便说一句,如果要登录用户,可以使用
Auth.auth().signIn(withEmail: email, password: password) { … }