这可能是一个简单的答案,所以提前道歉,但我被卡住了,因为我仍然对Firebase的工作原理感到满意。我想根据保存在那里的unix日期数据查询Firebase数据库,然后获取相关的“唯一ID”数据并将其放入数组中。
Firebase中的数据如下所示:
posts
node_0
Unix Date: Int
Unique ID Event Number: Int
node_1
Unix Date: Int
Unique ID Event Number: Int
node_2
Unix Date: Int
Unique ID Event Number: Int
到目前为止我所拥有的内容如下。查询部分似乎按预期工作。我正在努力的是如何将“唯一ID事件编号”数据放入数组中。这是最接近成功的方法,它基于此post,但我得到一个错误,即孩子没有“价值”成员。
// Log user in
if let user = FIRAuth.auth()?.currentUser {
// values for vars sevenDaysAgo and oneDayAgo set here
...
let uid = user.uid
//Query Database to get the places searched by the user between one and seven days ago.
let historyRef = self.ref.child("historyForFeedbackLoop/\(uid)")
historyRef.queryOrdered(byChild: "Unix Date").queryStarting(atValue: sevenDaysAgo).queryEnding(atValue: oneDayAgo).observeSingleEvent(of: .value, with: { snapshot in
if (snapshot.value is NSNull) {
print("error")
} else {
for child in snapshot.children {
if let uniqueID = child.value["Unique ID Event Number"] as? Int {
arrayOfUserSearchHistoryIDs.append(uniqueID)
}
}
}
})
} else {
print("auth error")
}
非常感谢任何想法!
答案 0 :(得分:4)
尝试使用: -
historyRef.queryOrdered(byChild: "Unix Date").queryStarting(atValue: sevenDaysAgo).queryEnding(atValue: oneDayAgo).observeSingleEvent(of: .value, with: { snapshot in
if let snapDict = snapshot.value as? [String:AnyObject]{
for each in snapDict{
let unID = each.value["Unique ID Event Number"] as! Int
arrayOfUserSearchHistoryIDs.append(unID)
}
}else{
print("SnapDict is null")
}
})
答案 1 :(得分:2)
我最终重新研究了如何根据this post中概述的方法阅读Firebase数据。我使用的实际工作代码如果它对其他人有帮助。
// Log user in
if let user = FIRAuth.auth()?.currentUser {
let uid = user.uid
// values for vars sevenDaysAgo and oneDayAgo set here
...
let historyRef = self.ref.child("historyForFeedbackLoop/\(uid)")
historyRef.queryOrdered(byChild: "Unix Date").queryStarting(atValue: sevenDaysAgo).queryEnding(atValue: oneDayAgo).observeSingleEvent(of: .value, with: { snapshot in
if (snapshot.value is NSNull) {
print("user data not found")
}
else {
for child in snapshot.children {
let data = child as! FIRDataSnapshot
let value = data.value! as! [String:Any]
self.arrayOfUserSearchHistoryIDs.append(value["Unique ID Event Number"] as! Int)
}
}
})
}