我想在用户决定更改用户名之前检查是否使用了用户名。由于某些原因,当进行检查并按下“完成”时,会出现错误横幅,指出用户名已被使用(即使我输入的用户名显然不是),同时我的打印语句“成功更改用户名”也在控制台中打印。用户名在数据库中成功更改,但是由于出现错误横幅,它阻止了我关闭推送的视图控制器。
我似乎无法弄清楚为什么无论如何都会显示错误。这是我编写的代码。
func textFieldDidEndEditing(_ textField: UITextField) {
let trimmedString = usernameTextField.text?.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression).lowercased()
guard trimmedString != "" else {
print("ERROR: Please enter a valid username")
usernameChanged = false
return
}
updatedUsername = trimmedString?.lowercased()
usernameChanged = true
}
func updateUsername() {
guard let updatedUsername = self.updatedUsername else { return }
guard let currentUid = Auth.auth().currentUser?.uid else { return }
guard usernameChanged == true else { return }
let reference = Database.database().reference().child("activeUsernames")
let query = reference.queryOrdered(byChild: "username").queryEqual(toValue: updatedUsername )
query.observe(.value, with: { (DataSnapshot) in
if DataSnapshot.exists() {
print("Username already exists")
self.errorBanner()
} else {
print("Username successfully changed")
reference.child(currentUid).child("username").setValue(updatedUsername)
USER_REF.child(currentUid).child("username").setValue(updatedUsername) { (err, ref) in
guard let userProfileController = self.userProfileController else { return }
userProfileController.fetchCurrentUserData()
self.navigationController?.popViewController(animated: true)
}
}
})
}
@objc func handleDone() {
view.endEditing(true)
if usernameChanged {
updateUsername()
}
}
答案 0 :(得分:1)
您正在滥用FirebaseRealtimeDatabase
API。
observe
应该传递实时事件,但是您需要检查用户名是否存在只是读取一次(请在此处https://firebase.google.com/docs/database/ios/read-and-write#read_data_once中检查操作方法)
因此,您在代码中看到的基本上是对设置的值感到困惑:)
不过还有一些Swift建议:
func textFieldDidEndEditing(_ textField: UITextField) {
// Here non-regex API is better
let trimmedString = usernameTextField.text?.trimmingCharacters(in: .whitespaceAndNewline)
guard trimmedString != "" else {
print("ERROR: Please enter a valid username")
return
}
updatedUsername = trimmedString?.lowercased()
}
// Swift willSet / didSet is better
var updatedUsername: String? {
willSet {
if updatedUsername != newValue {
usernameChange = true
}
}
}
var usernameChanged: Bool