【发布时间】:2017-08-20 03:20:30
【问题描述】:
我已将 Firebase 链接到我的应用。当我尝试从数据库中读取数据时,快照中存在数据。但是当一个孩子被读取时,它会返回 nil。
代码如下:
func checkForDuplicateScan(qrCode: String) {
DataService.ds.REF_SAMPLES.observeSingleEvent(of: .value, with: { (snapshot) in
if let dict = snapshot.value as? [String:Any] {
print(dict)
print(qrCode)
print(dict["\(qrCode)"])
if let sampleDict = dict[qrCode] as? [String:Any] {
print(sampleDict)
if let isScanned = sampleDict["scanned"] as? Bool {
if isScanned == true {
print("Already Scanned")
let alert = UIAlertController(title: "Already Redeemed", message: "This offer has already been redeemed by you. Stay tuned.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (alert) in
self.tabBarController?.selectedIndex = 0
}))
self.present(alert, animated: true, completion: nil)
} else {
print("New Scan")
self.updateQRCode(qrCode: qrCode)
}
} else {
print("Error: can't read/find 'scanned' ")
}
}else {
print("Error: Invalid Code Scanned")
let alert = UIAlertController(title: "Invalid QR Code Scanned", message: "The code that you've scanned is Invalid.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (alert) in
self.tabBarController?.selectedIndex = 0
}))
self.present(alert, animated: true, completion: nil)
}
} else {
print("Error: can't get dictionary from snapshot value")
}
})
}
这是控制台日志:
日志:
字典来自打印字典。
打印(字典)“test13”来自
打印(二维码)“零”来自
print(dict["\(qrCode)"])
这段代码昨天还在工作,但今天失败了。
帮帮我!!
编辑:这是我要读取的数据。
这也是 JSON 文件JSON FILE
更新:看来我在这里发现了问题。
当我运行这段代码时,什么都没有打印出来。
if let newDict = dict[qrCode] as? NSDictionary {
print(newDict)
}
但是,当我这样做时,字典是可以访问的。
if let newDict = dict["test10"] as? NSDictionary {
print(newDict)
}
注意 qrCode 是一个字符串,其值为 "test10"
怪怪的!!仍然无法弄清楚其背后的原因以及如何纠正。
【问题讨论】:
-
我不知道日志中的哪一行来自什么代码。
-
@FrankvanPuffelen 更新
-
您在问题中包含了 JSON 树的图片。请将其替换为实际的 JSON 作为文本,您可以通过单击 your Firebase Database console 中的导出 JSON 链接轻松获得。将 JSON 作为文本使其可搜索,让我们可以轻松地使用它来测试您的实际数据并在我们的答案中使用它,一般来说这只是一件好事。
标签: firebase swift3 firebase-realtime-database