如何将Firebase数据库值转换为UILabel文本?

时间:2017-03-09 18:17:48

标签: ios firebase swift3 firebase-realtime-database

我正在尝试从Firebase数据库中读取值。然后我想将UILabel文本更改为数据库子值。看起来很简单,但我无法弄清楚为什么值为空白。

这是我的Firebase JSON:

{
  "pilots" : {
    "HpPzn0XUqMgsKhUOpH75lHIhyFA3" : {
      "pilot" : "First Lastname",
      "weight" : 180
    }
  }
}

以下是Firebase规则,仅用于测试:

{
  "rules": {
    "pilots": {
        ".read": true,
        ".write": true

    }
   }
 }

最后是Swift 3代码,这可能是罪恶的丑陋。阅读和在线课程后的第一个应用程序。

import UIKit
import Firebase
import FirebaseCore
import FirebaseAuth
import FirebaseDatabase

class MainMenuViewController: UIViewController {


@IBOutlet weak var pilotUsername: UILabel!
@IBOutlet weak var dateTime: UILabel!
@IBOutlet weak var aircraftLabel: UILabel!
@IBOutlet weak var riskScoreInt: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    let ref = FIRDatabase.database().reference()
    let userID = FIRAuth.auth()?.currentUser?.uid

    ref.child("pilots").child(userID!).child("pilot").observeSingleEvent(of: .value, with: { (snapshot) in

        // Get user value
        let value = snapshot.value as? NSDictionary
        let username = value?["username"] as? String ?? ""

        self.pilotUsername.text = username

        print(username)
        // ...
    }) { (error) in
        print(error.localizedDescription)
    }





}
}

我只是使用Firebase文档中的示例代码。

之后有一行代码(在示例中)
let username = value?["username"] as? String ?? ""

即:

let user = User.init(username: username)

但它给了我一个错误。 “使用未解析的标识符'用户'”

我认为我不需要那行代码,因为在我所提供的示例和课程中没有使用它。

提前谢谢。这是我第一次发布Stack Overflow。

1 个答案:

答案 0 :(得分:0)

import FirebaseDatabase

class User {

    // MARK: Properties

    var firstname: String
    var lastname: String
    var username: String { return "\(firstname)\(lastname)" }

    // MARK: Initializers

    init(firstname: String, lastname: String) {

        self.firstname = firstname
        self.lastname = lastname
    }

    init?(snapshot: FIRDataSnapshot) {

        guard
            let firstname = snapshot.childSnapshot(forPath: "First").value as? String,
            let lastname = snapshot.childSnapshot(forPath: "Lastname").value as? String
        else { return nil }

        self.firstname = firstname
        self.lastname = lastname
    }
}

然后

ref.child("pilots").child(userID!).child("pilot").observeSingleEvent(of: .value, with: { [weak self] (snapshot) in

    if let user = User(snapshot: snapshot) {

        self?.pilotUsername.text = user.username
    }

}) { (error) in

    print(error.localizedDescription)
}