我想在按下按钮时获取用户的位置,我找到了一种方法来使用CLLocationManager,该代码完美地工作,直到设备没有网络连接,函数func locationManager(manager:CLLocationManager,didUpdateLocations)位置:[CLLocation])捕获错误
((NSError?)error = domain:“kCLErrorDomain” - 代码:2 )
如何在没有互联网连接的情况下获取设备位置?这是我使用的代码
import CoreLocation
class SesionViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: { (placemarks, error) -> Void in
if (error != nil) {
print("Error:" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as CLPlacemark
print(pm!.coordinate.latitude)
}else {
print("Error with data")
}
})
}
func startButtonPress(sender:UIButton!){
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.locationManager.stopUpdatingLocation()
}
}
Edit
我已经找到了解决方案,我只是不执行CLGeocoder() . reverseGeocodeLocation ...只是捕获位置var这样的位置
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(manager.location!.coordinate.latitude)
}
1 回答
来自Apple doc关于ClGeocoder的文章
将始终报告没有互联网访问的错误 . 您的位置数据仍然可用(如果您的设备配有GPS设备)