我具有此数据结构,但无法提取正确的值:
users
private
userID
birthday: "birthdayValue"
username: "nathan"
firstName: "Nathan"
etc...
我正在我的应用程序中进行搜索,以通过Firebase实时数据库通过用户名搜索用户:
let reference = Database.database().reference()
if(searchText != ""){
reference.child("users").child("private").queryOrdered(byChild: "username").queryStarting(atValue: searchText).queryEnding(atValue: searchText + "\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.value is NSNull{
//handles errors
return
}
else{
if let user = snapshot.value as? NSDictionary {
for child in user{
let resultsLocalArray: [String] = []
print(child.key)
print(child.value)
}
}
else{
//null
}
}
})
此刻,每当我搜索时,两个打印语句正在控制台中打印这两个结果:
wnszfmHilqNl6PG9khWtWkKUPtF3
{
birthday = 100;
dateCreated = "1579543450313.94";
description = nil;
email = "[email protected]";
firstName = Nathan;
instagramLink = nil;
lastLogin = "1579543450313.988";
lastName = Ellis;
profilePicURL = "url";
twitchLink = nil;
username = nathan;
youtubeLink = nil;
}
这是预期的,它将以NSDictonary形式显示usersID(键)和快照的值。我只想获取用户名,仅此而已。如何从该Firebase快照中提取用户名,以便可以将其用户名作为字符串添加到搜索控制器的数组中?
显然,它必须是动态的,因为userID总是不同的。
我需要更改数据模型吗?
仅打印用户名,最小的更改是:
print(resultsLocalArray["username"])
这会很好,但仍会检索到客户端的整个用户节点,客户端使用的带宽超过了严格需要的带宽。
[如果您发现自己经常只需要用户的username
,甚至可能需要整个用户的username
值列表,则可能要考虑存储仅包含用户名的节点。所以像:
users
userID: "nathan"
但是在当前设置中,您只为单个用户检索节点,因此我怀疑节省带宽是否值得额外的复杂性。
您的child.value
似乎也是一本词典,因此您可以通过以下方式访问它:
if let valueDict = child as? NSDictionary{
let username = valueDict["username"] as? String
// append username to results
}