这是我第一次使用firebase,我想要做的是将数据库中存储的4个值调用到单个字符串,这些代码和数据库的外观如下所示。我在数据库中启用了读写功能。任何帮助将不胜感激。
我从这里获得了一些代码Type 'Any' has no subscript members (firebase)
并且一直在关注将数据存储在数组https://youtu.be/XIQsQ2injLo
中的教程但到目前为止我没有成功。 感谢
import UIKit
import Firebase
import FirebaseDatabase
class ViewController: UIViewController {
@IBOutlet var Silver: UILabel!
@IBOutlet var Aqua: UILabel!
@IBOutlet var Orange: UILabel!
@IBOutlet var Purple: UILabel!
@IBAction func loadData(_ sender: Any) {
let databaseRef = FIRDatabase.database().reference()
databaseRef.queryOrderedByKey().observe(.childChanged, with: {
snapshot in
let content2 = (snapshot.value as? NSDictionary)?["aqua"] as? String ?? ""
let content3 = (snapshot.value as? NSDictionary)?["orange"] as? String ?? ""
let content4 = (snapshot.value as? NSDictionary)?["purple"] as? String ?? ""
let content = (snapshot.value as? NSDictionary)?["silver"] as? String ?? ""
print(content2)
print(content3)
print(content4)
print(content)
self.Silver.text = content
self.Aqua.text = content2
self.Orange.text = content3
self.Purple.text = content4
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let databaseRef = FIRDatabase.database().reference()
databaseRef.queryOrderedByKey().observe(.childChanged, with: {
snapshot in
let content = (snapshot.value as? NSDictionary)?["silver"] as? String ?? ""
let content2 = (snapshot.value as? NSDictionary)?["aqua"] as? String ?? ""
let content3 = (snapshot.value as? NSDictionary)?["orange"] as? String ?? ""
let content4 = (snapshot.value as? NSDictionary)?["purple"] as? String ?? ""
self.Silver.text = content
self.Aqua.text = content2
self.Orange.text = content3
self.Purple.text = content4
})
}
}
答案 0 :(得分:1)
您已使用.childChanged观察者尝试下面的代码
ref.observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let username = value?["username"] as? String ?? ""
// ...
}) { (error) in
print(error.localizedDescription)
}