Reputation: 19
I am trying to print my data from firebase into Xcode. However, I can never print the snapshot.value into my label (named as "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? It should print my data onto the label, but it never shows up. Please help, thanks.
Data in my firebase database
Upvotes: 0
Views: 551
Reputation: 1679
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. And ionic
is a dictionary [String: Double], not a text.
Hope this helps.
Upvotes: 1
Reputation: 1238
You need to cast your snapshot as Dictionary first.
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
Upvotes: 0