然后我查询firebase:
func getUserInfo(){
var tempUsers = [user]()
// query for the data
let itemRef = Database.database().reference(fromURL: "[url]").child("users")
itemRef.observe(.value, with: { snapshot in
for child in snapshot.children {
if let childSnapshot = child as? DataSnapshot,
let dict = childSnapshot.value as? [String: Any],
let sport = dict["Sport"] as? String,
let username = dict["username"] as? String{
let user = user(sport: sport, username: username)
tempUsers.append(user)
}
}
self.usersArray = tempUsers
}){ (error) in
print("the error is: \(error.localizedDescription)")
}
}
用户:
class user {
var username: String
var sport: String
var teamInfo: [teamInfo]
init(username: String, sport: String, teamInfo: [teamInfo])
{
self.username = username
self.sport = sport
self.teamInfo = [teamInfo]
}
}
struct teamInfo {
var AwayTeam: String
var HomeTeam = String
var Jersey = Int
}
我想知道如何在查询中获取Team信息,然后将其添加到User实例,我试图将“ Team”变成dict,但这不能给出我得到预期的结果。
答案 0 :(得分:1)
第一件事:username
中存在不一致之处。您的JSON用大写的Username
来拼写U
,而代码使用的是username
和小写的u
。由于Firebase区分大小写,因此您的代码现在永远不会获得正确的值。
除此之外,您还可以使用DataSnapshot.childSnapshot(forPath:)
从嵌套子项中获取值。
itemRef.observe(.value, with: { snapshot in
for child in snapshot.children {
if let childSnapshot = child as? DataSnapshot,
let dict = childSnapshot.value as? [String: Any],
let team = childSnapshot.childSnapshot(forPath: "Team/AwayTeam").value as? String;