我想通过从一个Firebase节点获取值并使用这些值从另一个Firebase节点获取信息来填充数组。我该怎么办?
[请帮助我,stackoverflow神。我快要哭了。
这是我的Firebase数据库的外观:
{
"MainTree" : {
"subTree1" : {
"JiRtkpIFLVFNgmNBpMj" : {
"PiRterKFLVFNgmFFFtu" : "PiRterKFLVFNgmFFFtu"
"TfRterKFLVFNgmFGFre" : "TfRterKFLVFNgmFGFre",
"X4RterKFLVFNgmaDFca" : "X4RterKFLVFNgmaDFca"
}
},
"subTree2" : {
"PiRterKFLVFNgmFFFtu" : {
"username" : "user1",
"uid" : "PiRterKFLVFNgmFFFtu"
},
"TfRterKFLVFNgmFGFre" : {
"username" : "user2",
"uid" : "TfRterKFLVFNgmFGFre"
},
"X4RterKFLVFNgmaDFca" : {
"username" : "user3",
"uid" : "X4RterKFLVFNgmaDFca"
}
}
}
}
我的通话功能
fetchAllBookmarks(uid: "JiRtkpIFLVFNgmNBpMj", completion: { (userdata) in
print("fetched all userdata! : ",userdata)
}) { (err) in
print("you failed yet again")
}
我的功能
func fetchAllInformation(uid: String, includeCurrentUser: Bool = true, completion: @escaping ([UserData]) -> (), withCancel cancel: ((Error) -> ())?) {
let ref = Database.database().reference().child("MainTree").child("subTree1").child(uid)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists(){
guard let dictionaries = snapshot.value as? [String: Any] else {
completion([])
return
}
var Values = [UserData]()
let group = DispatchGroup()
dictionaries.forEach({ (key, value) in
group.enter()
let ref = Database.database().reference().child("MainTree").child("subTree2").child(key)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let userDictionary2 = snapshot.value as? [String: Any] else { return }
let user = UserData(dictionary: userDictionary2)
Values.append(user)
}) { (err) in
print("Failed to fetch all user data from database:", (err))
cancel?(err)
}
})
group.notify(queue: .main) {
print("loop done")
completion(bookmarkedUsers)
}
}
}) { (err) in
print("Failed to fetch all data from database:", (err))
cancel?(err)
}
}
我的数据结构
struct UserData {
let uid: String
let username: String
init(dictionary: [String: Any]) {
self.uid = dictionary["id"] as? String ?? ""
self.username = dictionary["username"] as? String ?? ""
}
}
observeSingleEvent
可能只是在获取第一个条目。查看Firebase数据库文档here,您会发现他们使用observe
获取列表。尝试像这样遍历所有孩子:
ref.observe(.value) { snapshot in
for child in snapshot.children.allObjects as! [DataSnapshot] {
print(child.value)
let dict = child.value as? [String : AnyObject] ?? [:]
print(dict["title"])
}
}
因此,您要返回数组的任何地方都可以使用上述observe
方法,而您只希望单个数据输入的任何地方都可以使用observeSingleEvent
。>