想要从firebase数据库中提取QR值,但快照打印为nil

时间:2018-01-26 11:06:12

标签: ios swift firebase firebase-realtime-database

我想提取firebase数据库QR值的QR值 - > year-> month-> day-> QR:value enter image description here

func GetQR() {
    let date = getDate()

    let year =  String(describing: date.year)
    let month = String(describing:date.month)
    let day = String(describing:date.day)

    ref = Database.database().reference().child("QR Values").child(year).child(month).child(day)
    ref.observeSingleEvent(of: .value, with: { (snapshot) in

        // Get user value
        let value = snapshot.value as? String


            print(value)

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

    }

打印的快照为零。

2 个答案:

答案 0 :(得分:0)

您仍然需要在snapshot中查找从数据库中获取的QR属性:

ref = Database.database().reference().child("QR Values").child(year).child(month).child(day)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
    let value = snapshot.childSnapshot(forPath: "QR").value as? String

答案 1 :(得分:0)

由于变量 < / strong>是可选的, 天的值 不是可选的,它会导致 nil 。因此,解决方案是删除可选项。

   func GetQR() {

    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)

    let year =  "\(String(describing: components.year!))"
    let month = "\(String(describing: components.month!))"
    let day = "\(String(describing: components.day!))"

ref = Database.database().reference().child("QR Values").child(year).child(month).child(day)
ref.observeSingleEvent(of: .value, with: { (snapshot) in

    // Get user value
    let value = snapshot.value as? String


        print(value)

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

}