我创建了这个应用程序,它需要获得用户的位置 - 它的所有工作正常,事情是,从接受位置服务的使用,获得实际位置的时间需要5秒 - 这是正常的吗?我已经使用其他应用程序,它去得更快。
这是我的代码看起来像什么。
override func viewDidLoad() {
super.viewDidLoad()
// Ask for Location-Authorisation from the User.
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.requestLocation()
}
mapView.delegate = self
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue: CLLocationCoordinate2D = manager.location!.coordinate
let initialLocation = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude)
self.centerMapOnLocation(initialLocation)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("could not get location")
}
但从应用程序获取位置到放入centerMapOnLocation函数的时间,似乎很长。当获取用户的位置时,可以预期的是什么?我是在wifi连接上测试的,所以我知道不是因为网速太慢,也不是因为连接不好......。
有人有什么想法吗 :)
问候
试着设置精度,并使用locationManager.startUpdatingLocation()。我这样做,并在一秒钟内得到答案(在设备上)。
从文档中的 requestLocation():
此方法立即返回。调用此方法会使位置管理人获得一个位置修正。(可能需要几秒钟) 并将结果调用委托人的locationManager(_:didUpdateLocations:)方法。
所以基本上,你的代码一切正常,只是框架的构建方式。
如果你不想为了位置管理器而耽误应用的启动,可以考虑部署两个位置管理器(在应用委托中),责成一个快速生成位置,另一个准确生成位置。
locA.delegate = self
locA.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locA.requestWhenInUseAuthorization()
locA.startUpdatingLocation() // quick and multiple
locB.delegate = self
locB.desiredAccuracy = kCLLocationAccuracyBest
locB.requestWhenInUseAuthorization()
locB.requestLocation() // slow and single
以下的组合 3 km
准确度 startUpdatingLocation()
应该在根视图控制器准备就绪之前就返回一个位置。视图控制器的 B
经理很可能在用户启动应用后很久才返回一个位置。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
switch manager {
case locA:
locA.stopUpdatingLocation()
deviceLocation = locations.last! // set property with estimated loc
case locB:
deviceLocation = locations.last! // overwrite property with accurate loc
default:
break
}
}
而作为最后一层保护,你可以在客户端持久化位置。
private var deviceLocation_: CLLocation?
var deviceLocation: CLLocation? {
set {
deviceLocation_ = newValue
let c = ["lat": newValue.coordinate.latitude, "lon": newValue.coordinate.longitude]
UserDefaults.standard.set(c, forKey: "app.yourApp.coordinates")
} get {
if let l = deviceLocation_ {
return l
} else if let def = UserDefaults.standard.object(forKey: "app.yourApp.coordinates") as? [String: Double],
let lat = def["lat"],
let lon = def["lon"] {
return CLLocation(latitude: lat, longitude: lon)
} else {
return nil // or the coordinates to Lost island
}
}
}