首先,你是正確的,你不能在數據庫中存儲某些字符。按照火力地堡文檔,(https://firebase.google.com/docs/database/ios/structure-data)
如果你創建自己的密鑰,它們必須是UTF-8編碼,最多768個字節就可以了,不能包含。,$,#,[,] ,/或ASCII控制字符0-31或127.
但是,您可以看到,「@」符號不是其中之一。至於點,你可以有一個功能,用另一個字符替換點。例如, 」•」。下面是一個例子:
func createNewEmail(oldEmail: String) -> String{
return oldEmail.componentsSeparatedByString(".").joinWithSeparator("•")
}
它是如何將電子郵件拆分爲「email @ example」和「com」數組。然後,再加入他們的新角色,如果你需要的舊電子郵件創建「電子郵件@例如•COM」
,你可能只是做同樣的事情相反。
func getOldEmail(newEmail: String) -> String{
return newEmail.componentsSeparatedByString("•").joinWithSeparator(".")
}
然後,您可以格式化你的樹像這樣
emails:
[email protected]•com: UID123456789
最後,對於你原來的問題,該功能可以寫成這樣
func userLookUpByEmail (email: String) -> String {
let newEmail = createNewEmail(email)
var userID: String = "nil"
ref.child("emails").child(newEmail).observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
if snapshot.value != nil {
print(snapshot.value)
userID = snapshot.value as! String
}
else {
print ("user not found")
userID = "nil"
}
})
return userID
}
但是,它可能是你每次都會得到「零」。這是因爲observeSingleEventOfType是一個閉包。這意味着它運行在你的應用程序的後臺。因此,可能會在封閉內部更改之前返回userID。您可能想要在封閉內部運行基於userID的任何代碼,而不是返回userID。例如,而不是這樣做:
func userLookUpByEmail (email: String) -> String {
let newEmail = createNewEmail(email)
var userID: String = "nil"
ref.child("emails").child(newEmail).observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
if snapshot.value != nil {
print(snapshot.value)
userID = snapshot.value as! String
}
else {
print ("user not found")
userID = "nil"
}
})
return userID
}
doSomethingWith(lookUserUpByEmail([email protected]))
你可以這樣做:
func userLookUpByEmail (email: String){
let newEmail = createNewEmail(email)
var userID: String = "nil"
ref.child("emails").child(newEmail).observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
if snapshot.value != nil {
print(snapshot.value)
userID = snapshot.value as! String
doSomethingWith(userID)
}
else {
print ("user not found")
userID = "nil"
doSomethingWith(userID)
}
})
}
你的數據結構是不是有效的JSON。請用有效的JSON更新您的問題。 –
像這樣的東西似乎是最簡單的數據結構來做你想要的:http://stackoverflow.com/questions/37897656/firebase-security-find-other-users-via-email/37909700#37909700 –