【发布时间】:2016-12-05 07:26:18
【问题描述】:
我正在开发一个应用程序,我想在用户注册时存储用户的当前位置。
因此,一旦用户单击注册按钮,就会调用 locationManager.startUpdatingLocation() 并执行注册操作。
然而,即使在 didUpdateLocations 委托方法返回坐标之前,注册方法就会被触发,因此用户的位置在数据库中存储为 nil。
尝试在 didUpdateLocations 中调用注册方法是一团糟,因为该委托被多次调用。
func signup() {
self.getLocation()
let point = PFGeoPoint(latitude:locationLat, longitude:locationLon)
...
newUser[PF_USER_LOCATION] = point
newUser.signUpInBackground(block: { (succeed, error) -> Void in
if let errorInSignup = error {
...
} else {
...
}
})
}
func getLocation() {
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
locationLat = locValue.latitude
locationLon = locValue.latitude
}
我只添加了部分代码。
等待收到坐标后再调用注册功能的正确程序是什么?
requestWhenInUseAuthorisation() 在viewDidLoad() 内
【问题讨论】:
-
更改调用方法肯定有效
-
只有在收到当前位置时调用注册方法,才能使用闭包
-
如果您愿意只针对 ios9 及更高版本,您可以使用
requestLocationdeveloper.apple.com/reference/corelocation/cllocationmanager/… 否则您需要在didUpdateLocations中编写代码以检查适当的水平精度,然后停止位置更新并完成注册。当用户拒绝位置许可或无法在合理时间内确定位置时,您还需要提供适当的代码 -
笔记@Paulw11 感谢您的指出
标签: ios swift asynchronous cllocationmanager