我希望我的应用程序在活动和后台模式下定位(如果仅使用NSLocationAlwaysUsageDescription权限,则不显示myLocationButton )。我在 Info.plist 中设置:
<key>NSLocationAlwaysUsageDescription</key>
<string>$(PRODUCT_NAME) location use</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>$(PRODUCT_NAME) location use</string>
<key>UIBackgroundModes</key>
并添加 MapViewController
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.requestAlwaysAuthorization()
但是应用启动时,只显示第一个Location权限提示,重新打开应用后出现第二个权限提示。
更新:
override func viewDidLoad() {
super.viewDidLoad()
...
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
viewMap.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.new, context: nil)
self.startLocationUpdates()
...
}
func startLocationUpdates() {
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.activityType = CLActivityType.automotiveNavigation
self.locationManager.distanceFilter = distanceFilterMetr
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let myLocation: CLLocation = change?[NSKeyValueChangeKey.newKey] as! CLLocation
viewMap.camera = GMSCameraPosition.camera(withTarget: myLocation.coordinate, zoom: observeZoom)
mapRoute.coordinateLatitude = myLocation.coordinate.latitude
mapRoute.coordinateLongitude = myLocation.coordinate.longitude
viewMap.delegate = self
viewMap.settings.myLocationButton = true
viewMap.settings.compassButton = true
didFindMyLocation = true
}