【发布时间】:2016-05-14 07:37:31
【问题描述】:
我正在尝试在我的应用程序的新闻提要中实现与某些事件的动态距离。在我的模型类中,我有一个 distance 字段,一旦我加载我的 VC,我想在其中设置。我有一个名为parseData 的方法,在该方法中我调用了一个方法来设置我的模型类中的距离字段,它接受CLLocationCoordinate2D 的参数。
错误信息:fatal error: unexpectedly found nil while unwrapping an Optional value
这是该方法的 sn-p:
func parseData() {
DataService.ds.REF_LOBBYGAMES.queryOrderedByChild("distance").observeEventType(.Value, withBlock: { snapshot in
self.lobbyGames = []
// Parse Firebase Data
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let lobbyGameDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let lobbyGame = LobbyGameModel(lobbyKey: key, dictionary: lobbyGameDict)
lobbyGame.calculateDistanceAway(self.currentLocation)
self.lobbyGames.append(lobbyGame)
}
}
}
self.collectionView?.reloadData()
})
}
我想要做的是传递用户的当前位置,这样我就可以在模型类中进行计算。但是,lobbyGame.calculateDistanceAway(self.currentLocation)
行会崩溃,因为self.currentLocation 是nil。
这是我的viewDidLoad 方法:
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
navigationItem.title = "Events Near You"
collectionView?.alwaysBounceVertical = true
collectionView?.backgroundColor = UIColor.rgb(220, green: 220, blue: 220)
collectionView?.registerClass(FeedCell.self, forCellWithReuseIdentifier: CellId)
navigationController?.navigationBar.tintColor = UIColor.rgb(0, green: 171, blue: 236)
parseData()
}
这是我的didUpdateLocations 委托方法:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.currentLocation = manager.location?.coordinate
}
我不明白为什么 LocationManager 的坐标为零!我该如何解决?还是有更好的方法来做我想要完成的事情?任何帮助将不胜感激!
【问题讨论】:
-
您是否尝试过记录方法中传递的
locations数组 -
问题是parseData在
didUpdateLocations方法被调用之前就被命中了,所以location字段还是nil! -
那么你应该在
didUpdateLocations方法中调用parseData -
我也试过了,但
didUpdateLocations甚至没有被调用。我设置了断点,它只是从不进入方法。 -
那么您应该搜索有关 locationManager 为什么不起作用的问题。其他代码与此问题无关
标签: ios swift core-location cllocationmanager cllocation