我已将Firebase链接到我的应用程序。当我试图从数据库读取数据时,数据出现在快照中。但是当读一个孩子时,它返回nil。Swift 3:FirebaseDB在儿童出现时返回零点
下面的代码:
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' 从
打印(QRCODE)的 '零' 来自
打印出来(字典[ “\(QRCODE)”])
此代码在昨天工作,但今天失败。
帮帮我!
编辑:这是我正在尝试阅读的数据。
这里的JSON文件以及JSON FILE
更新:看起来我已经在这里发现了这个问题。
当我运行这段代码时,什么都不打印。
if let newDict = dict[qrCode] as? NSDictionary {
print(newDict)
}
但是,当我这样做时,字典是可访问的。
if let newDict = dict["test10"] as? NSDictionary {
print(newDict)
}
注意QRCODE是一个具有值串 “test10”
奇怪ASF !!仍然无法弄清其背后的原因以及如何纠正这一问题。
我不知道日志中的哪一行来自哪个代码。 –
@FrankvanPuffelen已更新 –
您在问题中包含了JSON树的图片。请用实际的JSON替换为文本,您可以通过单击[您的Firebase数据库控制台](https://console.firebase.google.com/project/_/database/data/)中的导出JSON链接轻松获取该文本。 。将JSON作为文本可以搜索,使我们能够轻松使用它来测试您的实际数据,并将其用于我们的答案中,并且通常只是一件好事。 –