【问题标题】:Firebase Database suddenly returning nilFirebase 数据库突然返回 nil
【发布时间】:2018-02-25 21:00:48
【问题描述】:

直到两天前,我的代码运行良好,没有任何问题,当我知道我的 Firebase 节点中存在该值时,我的代码开始返回 nil。我已经好几周没有碰过代码了,最近也没有对它进行过任何更改。我最近将我的 Xcode 升级到 9,但仍在运行 Swift 3。

我在viewDidLoad() 上方声明了值radiusDistanceNumber

class viewController: UIViewController {

var radiusDistanceNumber: Int()

override func viewDidLoad()
 super.viewDidLoad {

}
    func radiusValue(){
        let user = Auth.auth().currentUser
        guard let uid = user?.uid else{
            return
        }
        let ref = Database.database().reference().child("Users").child(uid)
        ref.observeSingleEvent(of: .value, with: {snapshot in
            print("this is the snapshot value \(snapshot.value)")
            //returns correct value of 14
            if let dictionary = snapshot.value as? [String: AnyObject] {
                self.radiusDistanceNumber = dictionary["radiusDistance"] as? Int

                print(self.radiusDistanceNumber)
                //returns nil
                if self.radiusDistanceNumber == nil {
                    //let the user know it may be an error in connection
                    let alertController = UIAlertController(
                        title: "Error",
                        message: "Data not loading properly, make sure you have a strong connection and try again", preferredStyle: .alert)
                    let cancelAction = UIAlertAction(title: "Got it", style: .cancel, handler: nil)
                    alertController.addAction(cancelAction)
                    self.present(alertController, animated: true, completion: nil)

                } else{
                // pass the value to the slider so the user can see the distance
                let radiusDistanceNumberFloat = Float(self.radiusDistanceNumber!)
                self.radiusSlider.value = radiusDistanceNumberFloat
                self.radiusLabel.text = String(self.radiusSlider.value)
                    }
                }
            })
        }

再一次,这段代码在几周前就可以工作了

【问题讨论】:

  • 你的行 print("this is the snapshot value (snapshot.value)") 上的 snapshot.value 是否等于 14?如果是,您为什么尝试将其转换为下一行的字典?如果不是,它等于什么? :)
  • 我不认为上面的代码应该编译。它会给你var radiusDistanceNumber: Int()的错误吗?
  • 如果你在if let dictionary = snapshot.value as? [String: AnyObject]中尝试Any而不是AnyObject,看看结果如何?
  • 我觉得你应该把var radiusDistanceNumber: Int()改成var radiusDistanceNumber = Int()
  • @3stud1ant3 将其从 :Int() 更改为 = Int() 成功了!将其作为答案提交,以便我标记它

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

我认为您应该在代码中进行这些更改。您当前错误地声明了radiusDistanceNumber,所以

替换

var radiusDistanceNumber: Int()

var radiusDistanceNumber = Int()

我认为你也应该 替换

if let dictionary = snapshot.value as? [String: AnyObject]

if let dictionary = snapshot.value as? [String: Any]

【讨论】:

    猜你喜欢
    • 2018-12-14
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    相关资源
    最近更新 更多