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