我正在尝试解决我希望使用跨两个节点的匹配信息填充集合视图单元格并且需要在“播放器”节点中多次读取的问题。
以下是我的Firebase数据库结构
{
Players:
LpWgezRkC6EWS0sjXEWxhFl2: {
userName: 'John Doe'
teamId: '234'
teamName: 'Revenge'
teamLogo: 'star.png'
etc...
},
RfskjEWSkdsjkjdskjsd12fg: {
userName: 'Jane Doe'
teamId: '987'
teamName: 'Frills'
teamLogo: 'jag.png'
etc...
}
},
Matches:
12345: {
User1: 'LpWgezRkC6EWS0sjXEWxhFl2'
User2: 'RfskjEWSkdsjkjdskjsd12fg'
date: '11/10/17'
WeekId: 19
etc...
}
}
}
正如您所看到的,“匹配”节点包含“玩家”信息,所以在集合视图中我希望显示播放器1与播放器2的信息。
到目前为止我的代码是:
self.ref.queryOrdered(byChild: "WeekId").queryEqual(toValue: 19).observe(.value, with: { snapshot in
var items: [Match] = []
for item in snapshot.children {
let snapshotValue = (item as! DataSnapshot).value as? NSDictionary
let pId1 = snapshotValue!["User1"] as! NSString
let pId2 = snapshotValue!["User2"] as! NSString
let match = Match(snapshot: item as! DataSnapshot)
items.append(match)
}
self.matches = items
self.collectionView?.reloadData()
}
我不确定如何对“玩家”节点进行第二次查询(我需要2)因为它需要查找两个玩家信息,所有这些都没有超越let match = Match(snapshot: item as! DataSnapshot)
函数,否则它会失败吗?
任何人都可以帮忙!
答案 0 :(得分:1)
您可以添加
self.ref.queryOrdered(byChild: "WeekId").queryEqual(toValue: 19).observe(.value, with: { snapshot in
var items: [Match] = []
for item in snapshot.children {
let snapshotValue = (item as! DataSnapshot).value as? NSDictionary
let pId1 = snapshotValue!["User1"] as! NSString
let pId2 = snapshotValue!["User2"] as! NSString
fetchUserProfile(withUID: pId1, completion: { (userDict1) in
// Here you get the userDict 1
self.fetchUserProfile(withUID: pId2, completion: { (userDict2) in
//Here you get the user dict 2
let match = Match(snapshot: item as! DataSnapshot)
items.append(match)
})
})
}
self.matches = items
self.collectionView?.reloadData()
})
//获取完成的用户个人资料
func fetchUserProfile(withUID uid: String, completion: @escaping (_ profileDict: [String: Any]) -> Void) {
// New code
Database.database().reference().child(uid).observe(.value, with: { snapshot in
// Here you can get the snapshot of user1
guard let snapDict = snapshot.value as? [String: Any] else {return}
completion(snapDict)
})
}
我认为这不是解决这个问题的正确方法。我建议你捕获所有用户的pID并将其保存在UserProfiles数组中。需要时,您可以从该阵列中获取用户配置文件。 希望它有所帮助。