我正在使用swift为iOS 9.3编写应用程序,需要一张 Map 来显示用户位置 . 我初始化CLLocationManager及其委托,我配置info.plist隐私 - 位置使用说明字符串并调用requestWhenInUseAuthorization但它不显示任何授权请求 .
这是我的代码:
import UIKit
import MapKit
class DetailController: UIViewController, CLLocationManagerDelegate {
var locManager: CLLocationManager!
@IBOutlet var myMap: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mostraPosizione()
}
func mostraPosizione(){
locManager = CLLocationManager()
locManager.delegate = self
locManager.desiredAccuracy = kCLLocationAccuracyBest
let authorizationStatus = CLLocationManager.authorizationStatus()
if (authorizationStatus == CLAuthorizationStatus.NotDetermined) {
locManager.requestWhenInUseAuthorization()
} else {
locManager.startUpdatingLocation()
}
myMap.showsUserLocation = true
}
func locManager(manager: CLLocationManager,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if (status == CLAuthorizationStatus.NotDetermined) {
locManager.requestWhenInUseAuthorization()
} else {
locManager.startUpdatingLocation()
}
}
}
以及来自我的info.plist的截图
Xcode输出:
尝试在不提示位置授权的情况下启动MapKit位置更新 . 必须首先调用 - [CLLocationManager requestWhenInUseAuthorization]或 - [CLLocationManager requestAlwaysAuthorization] .
我正在iPhone 5(iOS 9.3)模拟器上测试它 .
What's the problem with this stuff? 有没有人有任何建议?
3 回答
我想是因为
是
nil
所以你的requestWhenInUseAuthorization()
从未被调用过 .应该工作 .
Edit :
如果用户拒绝请求,您还应该处理此案例
实际上,一旦用户拒绝授权,您就无法再次显示弹出窗口,用户必须进入应用程序设置并自行设置使用其位置的授权 . 但是,您现在可以直接从应用程序链接到设置,因此对用户来说更容易 .
将NSLocationWhenInUseUsageDescription键添加到info.plist是解决方案 .
试试这个尺码:
请求未显示的原因是因为在调用请求时未完成加载视图 . 使用viewDidAppear()修复了该问题 .
我也对代码进行了一些更改,这看起来效果很好 . 我只对下面的代码进行了更改,其他功能保持不变 .
我在Swift 3中编写这段代码,但是这些代码是相同的 .