未经用户许可,您不能使用位置跟踪。
以下是有关如何为AR 应用 和NON-AR 应用 正确设置它的一些提示:
在 iOS 11 及更高版本中,您需要执行以下操作才能使定位正常工作:
- 将密钥添加到您的
info.plist 并请求位置管理器的授权以启动它。 info.plist 中有两个Property List Keys 用于位置授权。 需要其中一个或两个键。在非 AR 应用中,如果两个键都不存在,您可以调用 startUpdatingLocation 方法,但位置管理器实际上不会启动。它也不会向代理发送失败消息(因为它从未启动,所以它不会失败)。 如果您添加一个或两个密钥但忘记明确请求授权,它也会失败。
在info.plist 文件中使用这两个Property List Keys。自 iOS 11 发布以来就使用它们:
<key>NSLocationWhenInUseUsageDescription</key>
<string>App needs an access to your location (in foreground)</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>App needs an access to your location (in background)</string>
这两个Property List Keys 早前已弃用(不要使用这些键):
<key>NSLocationUsageDescription</key>
<string>App needs an access to your location (in background)</string>
<key>NSLocationAlwaysUsageDescription</key>
<true/>
AR 应用代码如下所示:
let configuration = ARWorldTrackingConfiguration()
func session(_ session: ARSession, didFailWithError error: Error) {
switch error.code {
case 101:
configuration.worldAlignment = .gravity
restartSession()
default:
configuration.worldAlignment = .gravityAndHeading
restartSession()
}
}
func restartSession() {
self.sceneView.session.pause()
self.sceneView.session.run(configuration, options: [.resetTracking,
.removeExistingAnchors])
}
对于非 AR 应用,请使用以下两种实例方法:requestAlwaysAuthorization()(在应用运行时请求使用位置服务的权限)和requestWhenInUseAuthorization()(在应用处于前台时请求使用位置服务的权限)。
您的代码用于非 AR 应用应如下所示:
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
func updateMyLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
if locationManager.respondsToSelector(#selector(CLLocationManager.requestWhenInUseAuthorization)) {
locationManager.requestWhenInUseAuthorization()
} else {
locationManager.startUpdatingLocation()
}
}
}
另外,您可以申请Always Authorization:
let locationManager = CLLocationManager()
func enableLocationServices() {
locationManager.delegate = self
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
// Request when-in-use authorization initially
locationManager.requestWhenInUseAuthorization()
break
case .restricted, .denied:
// Disable location features
disableMyLocationBasedFeatures()
break
case .authorizedWhenInUse:
// Enable basic location features
enableMyWhenInUseFeatures()
break
case .authorizedAlways:
// Enable any of your app's location features
enableMyAlwaysFeatures()
break
}
}
希望这会有所帮助。