【发布时间】:2018-09-12 00:00:04
【问题描述】:
我的应用有问题。当我在第一个 ViewController 上初始化应用程序时,我使用此代码和一个名为“By”的对象和一个名为“byer”的对象数组从我的 Firebase 服务器获取一些数据:
func download() {
byer.removeAll()
self.Handle = self.ref?.child("Byer").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let by = By()
by.Latitude = dictionary["Latitude"]?.doubleValue
by.Longitude = dictionary["Longitude"]?.doubleValue
by.Name = snapshot.key
let coordinate = CLLocation(latitude: by.Latitude!, longitude: by.Longitude!)
let distanceInMeter = coordinate.distance(from: self.locationManager.location!)
by.Distance = Int(distanceInMeter)
byer.append(by)
byer = byer.sorted(by: {$0.Distance! < $1.Distance! })
DispatchQueue.main.async {
selectedCity = byer[0].Name!
self.performSegue(withIdentifier: "GoToMain", sender: nil)
}
}
})
}
这一切都很好。但是当我稍后在应用程序中获取数据库中的值时,问题就来了。我使用带有此代码的按钮:
if byTextfield.text != "" && latitude != nil && longitude != nil {
ref?.child("Byer").child(byTextfield.text!).child("Latitude").setValue(latitude)
ref?.child("Byer").child(byTextfield.text!).child("Longitude").setValue(longitude)
}
但由于某种原因,应用程序崩溃并且一条红线越过这条线:
let coordinate = CLLocation(latitude: by.Latitude!, longitude: by.Longitude!)
从顶部的下载功能。和文字: “线程 1:致命错误:在展开可选值时意外发现 nil。”。
我尝试使用以下方法删除观察者:
override func viewDidDisappear(_ animated: Bool) {
self.ref?.removeObserver(withHandle: self.Handle)
}
但这似乎没有帮助。有什么建议?
【问题讨论】:
标签: ios swift firebase firebase-realtime-database observers