简体   繁体   English

iOS Firebase Snapshot.value

[英]iOS Firebase Snapshot.value

I am trying to print my data from firebase into Xcode. 我正在尝试将数据从Firebase打印到Xcode。 However, I can never print the snapshot.value into my label (named as "polar"). 但是,我永远无法将snapshot.value打印到我的标签(名为“ polar”)中。 Here is my code: 这是我的代码:

import UIKit
import FirebaseDatabase

class ViewController: UIViewController {


@IBOutlet var polar: UILabel!
var ref:DatabaseReference?
var databaseHandle:DatabaseHandle?
var postData = [String]()

override func viewDidLoad() {
    super.viewDidLoad()


    let ref = Database.database().reference()

    ref.child("Total gallons:").observe(.childAdded, with: { (snapshot) in

        let ionic = snapshot.value as? String
        self.polar.text = ionic

Why isn't my self.polar.text working? 为什么我的self.polar.text无法正常工作? It should print my data onto the label, but it never shows up. 它应该将我的数据打印到标签上,但从不显示。 Please help, thanks. 请帮忙,谢谢。

Data in my firebase database 我的Firebase数据库中的数据

点击此处查看我的Firebase数据库中的数据

You need to cast your snapshot as Dictionary first. 您需要先将快照转换为Dictionary

You could do: 您可以这样做:

guard let ionic = snapshot.value as? [String: Double] else { return }
print(ionic) // This will print snapshot. 
//You still need to add logic here to parse values from dictionary.

DispatchQueue.main.async {
     // Update UI elements here
}

self.polar.text = ionic self.polar.text =离子

You could try this code: 您可以尝试以下代码:

ref.child("Total gallons").observe(.childAdded, with: { (snapshot) in
    if let ionic = snapshot.value as? [String: Double] {
        self.polar.text = ionic
    }
})

You should notice that "Total gallons" doesn't have ":" at the end. 您应该注意, "Total gallons"末尾没有“:”。 And ionic is a dictionary [String: Double], not a text. ionic是字典[String:Double],而不是文本。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM