要在Swift中标记的Firebase快照

时间:2017-05-22 18:15:15

标签: swift firebase firebase-realtime-database uilabel

我是Firebase的新手,但学得很快。但是,这个问题让我望而却步,过去三天我一直在寻找答案,我相信这是一个简单的解决方案,我只是忽略了。我想从Firebase数据库返回一个值来填充标签,以及用于后续视图中的计算。

我可以在控制台中打印快照,但是当我将其分配给文本标签时,标签是空白的。为了清楚起见,我不想用这些数据填充表格。我想从数据库中提取特定数据并将其显示在标签中,并将其用于计算。

这是我的代码:

@IBOutlet weak var textLabel: UILabel!

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

override func viewDidLoad() {
    super.viewDidLoad()

    getIncome()
}

func getIncome() {
    ref.child("Users").child("Family1").child("Income").observeSingleEvent(of: .value, with: { snapshot in

        print(snapshot)     // replace this with textLabel or other item
        let m = snapshot.value as? String
        self.textLabel.text = m
    })
}

这是来自Firebase的我的JSON树:

Screenshot of Firebase Database Structure

2 个答案:

答案 0 :(得分:1)

您的数据库已将Income存储为整数,因此当您尝试将snapshot.value强制转换为字符串时,它将返回nil,因为它是一个整数。因此,您首先必须将其转换为Int,然后您可以将其连接到字符串。

let ref = FIRDatabase.database().reference().child("Users").child("Family1").child("Income")

ref.observeSingleEvent(of: .value, with: { (snapshot) in

    if let income = snapshot.value as? Int {

        self.textLabel.text = "Your income is: \(income)"
    }
})

然后标签显示Your income is: 456789

实施例

import UIKit
import MapKit
import Firebase

class ViewController: UIViewController {

    @IBOutlet weak var textLabel: UILabel!

    @IBOutlet weak var calculateButton: UIButton!

    var income: Int?

    override func viewDidLoad() {
        super.viewDidLoad()

        calculateButton.isHidden = true // Prevents user tapping it until we have data from firebase

        getIncome { (income) in

            self.income = income

            if let income = income {

                self.textLabel.text = "Your income is: \(income)"
            }

            self.calculateButton.isHidden = false
        }
    }

    func getIncome(completion: @escaping (Int?)->()){

        let ref = FIRDatabase.database().reference().child("Users").child("Family1").child("Income")

        ref.observeSingleEvent(of: .value, with: { (snapshot) in

            completion(snapshot.value as? Int)
        })
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "CalculateSegue" {

            guard

                let income = income,

                let vc = segue.destination as? CalculateViewController

            else {

                return
            }

            vc.income = income
        }

    }
}

class CalculateViewController: UIViewController {

    @IBOutlet weak var incomeLabel:UILabel!

    var income: Int!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.incomeLabel.text = "\(income)"
    }
}

Storyboard

ViewController

CalculateViewController

答案 1 :(得分:1)

哦,快!我想我明白了。使用异步数据库时,我想我必须等到数据库完成加载后再尝试显示数据或根据该数据进行计算。或许有一个术语或更好的方法,但这是我的解决方案。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "prototypeCell", for: indexPath) as! Setup106TableViewCell

    if indexPath.section == 0 {
        let (dailyChoreName, dailyChoreMultiplier, _, _) = dailyChores[indexPath.row]
        cell.titleLabel.text = dailyChoreName
        if income != nil {
            cell.detailLabel.text = "\(Int(round((Double(income!) * nationalAvg * mpsMagicNumber * Double(dailyChoreMultiplier) / 52) / 5) * 5))"
        } else {
            tableView.reloadData()      // this was the issue
        }

    } else if indexPath.section == 1 {
        let (dailyHabitName, dailyHabitMultiplier, _, _) = dailyHabits[indexPath.row]
        cell.titleLabel.text = dailyHabitName
        if income != nil {
            cell.detailLabel.text = "\(Int(round((Double(income!) * nationalAvg * mpsMagicNumber * Double(dailyHabitMultiplier) / 52) / 5) * 5))"
        } else {
            tableView.reloadData()      // this was the issue
        }

    } else {
        let (weeklyChoreName, weeklyChoreMultiplier, _, _) = weeklyChores[indexPath.row]
        cell.titleLabel.text = weeklyChoreName
        if income != nil {
            cell.detailLabel.text = "\(Int(round((Double(income!) * nationalAvg * mpsMagicNumber * Double(weeklyChoreMultiplier) / 52) / 50) * 50))"
        } else {
            tableView.reloadData()      // this was the issue
        }
    }
    return cell
}

我必须在继续之前添加' tableView.reloadData`参数。好的。