[英]Firebase querying for unique Username swift
我搜索了這個問題,但他們都沒有一個對我有用的答案。
我想在用戶注冊帳戶時這樣做,它會在創建帳戶之前檢查他們輸入的用戶名是否已經存在。 我曾嘗試在firebase中使用查詢,但我似乎無法讓它工作。
這是我的firebase數據的圖像: 我的firebase數據樹
我如何使用查詢來查找密鑰“用戶名”的字符串?
您可以這樣,使用完成塊創建一個功能以檢查您的Firebase數據庫中是否已存在用戶名,並在此基礎上創建新用戶
func checkUserNameAlreadyExist(newUserName: String, completion: @escaping(Bool) -> Void) {
let ref = FIRDatabase.database().reference()
ref.child("users").queryOrdered(byChild: "username").queryEqual(toValue: newUserName)
.observeSingleEvent(of: .value, with: {(snapshot: FIRDataSnapshot) in
if snapshot.exists() {
completion(true)
}
else {
completion(false)
}
})
}
現在只需在創建新用戶時調用此函數:
self.checkUserNameAlreadyExist(newUserName: "Johnson") { isExist in
if isExist {
print("Username exist")
}
else {
print("create new user")
}
}
我是這樣做的:
var text = "Your username"
let dbRef = FIRDatabase.database().reference().child("users")
dbRef.queryOrdered(byChild: "name").queryEqual(toValue: text).observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() {
// Name doesn't exist
}
if let data = snapshot.value as? [String: [String: String]] {
// it should exist if it reaches here
}
})
確保在數據庫規則中索引“name”上的“users”節點以進行性能優化。
我接下來這樣做:
注冊功能:
@IBAction func signUpButtonTapped(_ sender: Any) {
User.getItemByLogin(for: userLogin.text!,
completion: { userItem in
if userItem == nil {
self.createAndLogin()
} else {
self.showAlertThatLoginAlreadyExists()
}
})
}
private func createAndLogin() {
FIRAuth.auth()!.createUser(withEmail: userEmail.text!,
password: userPassword.text!) { user, error in
if error == nil {
// log in
FIRAuth.auth()!.signIn(withEmail: self.userEmail.text!,
password: self.userPassword.text!,
completion: { result in
// create new user in database, not in FIRAuth
User.create(with: self.userLogin.text!)
self.performSegue(withIdentifier: "fromRegistrationToTabBar", sender: self)
})
} else {
print("\(String(describing: error?.localizedDescription))")
}
}
private func showAlertThatLoginAlreadyExists() {
let alert = UIAlertController(title: "Registration failed!",
message: "Login already exists.",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
我的用戶類功能。 它的類似API:
static func getItemByLogin(for userLogin: String,
completion: @escaping (_ userItem: UserItem?) -> Void) {
refToUsersNode.observeSingleEvent(of: .value, with: { snapshot in
for user in snapshot.children {
let snapshotValue = (user as! FIRDataSnapshot).value as! [String: AnyObject]
let login = snapshotValue["login"] as! String // getting login of user
if login == userLogin {
let userItem = UserItem(snapshot: user as! FIRDataSnapshot)
completion(userItem)
return
}
}
completion(nil) // haven't founded user
})
}
在你的方式你應該用username
交換login
。
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.