ios - Firebase 数据库突然返回 nil

标签 ios swift firebase firebase-realtime-database

直到两天前,我的代码工作正常,没有任何问题,当我知道我的 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)
                    }
                }
            })
        }

同样,这段代码几周前就可以工作了

最佳答案

我认为您应该在代码中进行这些更改。您目前正在错误地声明 radiusDistanceNumber

替换

var radiusDistanceNumber: Int()

var radiusDistanceNumber = Int()

我觉得你也应该 替换

如果让 dictionary = snapshot.value as? [字符串:AnyObject]

如果让 dictionary = snapshot.value as? [字符串:任意]

关于ios - Firebase 数据库突然返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46260400/

相关文章:

iphone - 更改MFMailComposeViewController的标题

ios - 为 ios 构建时如何设置标志 -ObjC -all_load

ios - Swift:我应该为 Firebase 管理器类使用静态成员吗​​?好的程序设计

android - 在 Android 中从 Firebase 实时数据库中检索数据

web - Firebase 存储网站 : How to upload a file

java - 找不到包名称 'com.example.pc.fireApp' 的匹配客户端

iOS 10 - 每 "x"分钟重复一次通知

ios - 将按钮数组添加到适当的表行

ios - 无法使用 Today Extension 的共享应用组共享数据

swift - 为什么标签没有出现在全屏模式下?