从Firebase检索数据返回nil

时间:2019-04-21 06:43:46

标签: swift firebase firebase-realtime-database

下面是我尝试测试的代码。

树:

{
  "WorkingTime" : {
    "CloseTime" : 20,
    "SpaceTime" : 30,
    "StartTime" : 7
  }
}
override func viewDidLoad(){
        super.viewDidLoad()
        ref = Database.database().reference()
        handel = ref.child("WorkingTime").observe(.value, with: { snapshot in
            if let dict = snapshot.value as? [String:Any]{
                let startTimeFB = dict["StartTime"] as? String
                let endTimeFB = dict["CloseTime"] as? String
                print("\(startTimeFB ?? "nill") and \(endTimeFB ?? "nill")"
            }
        })
}

显然,它打印了nill and nill

1 个答案:

答案 0 :(得分:2)

键名和类型转换似乎是两个问题。请尝试以下代码,

override func viewDidLoad(){
        super.viewDidLoad()

        ref = Database.database().reference()

        handel = ref.child("WorkingTime").observe(.value, with: { snapshot in
            if let dict = snapshot.value as? [String:Any]{
                let startTimeFB = dict["StartTime"] as? Int
                let closeTimeFB = dict["CloseTime"] as? Int
                print("\(startTimeFB ?? 0) and \(closeTimeFB ?? 0)"
            }
        })
}