【发布时间】:2017-04-11 09:36:47
【问题描述】:
我希望我的应用程序在活动和后台模式下获取位置(如果仅使用 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
}
【问题讨论】:
-
您只需要请求“始终”授权。这使您的应用可以在前台和后台使用位置。
-
@Paulw11 我写的是如果只使用 NSLocationAlwaysUsageDescription 权限然后 myLocationButton 不显示(位置更新但按钮不显示)iOS 10.3 swift 3
-
您如何决定是否显示该按钮?我可以向您保证,前台和后台位置只需要始终进行身份验证。
-
@Paulw11 请更新我的代码。谢谢!!!
-
注意在教程中他们实现了
didChangeAuthorizationStatus委托方法并使用它来启用mylocation按钮。您是否实施了该方法并针对您请求的“始终”授权进行了更改?
标签: ios swift core-location info-plist