我已经为应用程序创建了注册/登录功能。
在此处创建用户:
Auth.auth().createUser(withEmail: userEmail, password: userPassword) { (user, error) in
if error == nil {
print("You have successfully signed up")
//add display name to this user
let user = Auth.auth().currentUser
if let user = user {
let changeRequest = user.createProfileChangeRequest()
changeRequest.displayName = userUsername
changeRequest.commitChanges { error in
if error != nil {
print("Error adding display name")
} else {
// Profile updated.
}
}
}
let uid = (Auth.auth().currentUser?.uid)!
let newUserRef = self.userRef.child(userUsername)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyy HH:mm:ss"
let timeZone = TimeZone(identifier: "Eastern Daylight Time")
dateFormatter.timeZone = timeZone
newUserRef.setValue(["uid": uid, "email": userEmail, "first": userFirst, "last": userLast, "username": userUsername, "created": String(describing: dateFormatter.string(from: Date()))])
usernamesRef.updateChildValues([userUsername:uid])
self.signIn(userEmail: userEmail, userPassword: userPassword)
}
要登录,我正在这样做:
Auth.auth().signIn(withEmail: userEmail, password: userPassword) { (user, error) in
if error == nil {
//Print into the console if successfully logged in
print("You have successfully logged in")
let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoggedIn")
self.present(vc!, animated: false, completion: nil)
} else {
//Tells the user that there is an error and then gets firebase to tell them the error
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
在这里我检索当前用户的显示名称(在单独的视图控制器中):
ref = Database.database().reference()
let user = Auth.auth().currentUser
//for testing purposes
if ((user) != nil) {
// User is signed in.
print("Signed in")
} else {
// No user is signed in.
print("Not signed in")
}
let displayName = user?.displayName ?? "nil"
ref.child("users").child(displayName!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let userFirst = value?["first"] as? String ?? ""
let userLast = value?["last"] as? String ?? ""
let userUsername = value?["username"] as? String ?? ""
let userEmail = value?["email"] as? String ?? ""
let userCreated = value?["created"] as? String ?? ""
let userUID = value?["uid"] as? String ?? ""
self.name.text = "\(userFirst) \(userLast)"
self.username.text = "\(userUsername)"
self.email.text = "\(userEmail)"
self.created.text = "\(userCreated)"
self.uid.text = "\(userUID)"
}){ (error) in
print(error.localizedDescription)
}
情况1:使用注册屏幕创建新用户时,它将创建用户,然后登录用户,然后更改场景以尝试从输入的Firebase中检索信息。所有信息均正确输入,显示在Firebase中,但未检索到现场。
情况2:在已经创建了用户之后,使用登录屏幕,它可以正确登录并更改场景并正确检索所有需要的信息。
为什么会这样?为什么在创建用户然后登录后以及已经创建并登录用户后仍无法检索它们。
谢谢!