我的Swift-iOS应用程序旨在显示用户在地图上的位置。但是,XCode调试控制台告诉我,我需要请求权限才能显示用户的位置。我想,我这样做,但对话永远不会出现。
这是错误消息,在ViewController下面我调用CLLocationManager::requestWhenInUseAuthorization()
错误:
2014-06-30 21:25:13.927 RowingTracker2 [17642:1608253]尝试在不提示位置授权的情况下启动MapKit位置更新。必须首先调用 - [CLLocationManager requestWhenInUseAuthorization]或 - [CLLocationManager requestAlwaysAuthorization]。
视图控制器:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var mapview: MKMapView = nil
var locationmgr : CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationmgr = CLLocationManager()
locationmgr.requestWhenInUseAuthorization()
mapview.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
如何申请授权使用该位置?你可以找到完整的项目here。(Commit)
甚至使ViewController从CLLocationManagerDelegate
继承并将委托设置为self
,如here所示也无济于事。
从iOS 8开始,您必须调用其中一个请求...函数,并将相应的条目添加到Info.plist文件中,NSLocationWhenInUseUsageDescription
或NSLocationAlwaysUsageDescription
。
有关更多信息,请参阅参考here
确保这一点
Debug > Location
下的模拟器中执行此操作。调试区域:
您需要使用requestWhenInUseAuthorization并且还需要在yourapp-Info.plist上创建一个名为NSLocationWhenInUseUsageDescription的值
我使用NSLocationAlwaysUsageDescription
作为在请求许可时弹出的文本,例如
“我希望得到许可,可以24/7全天候监视你”
我还会添加NSLocationWhenInUseUsageDescription
作为消息的值。
正如David Berry,Cayke Prudente和Levi Johnson所说,我只需要将NSLocationAlwaysUsageDescription
添加到我的Info.plist
文件中。要了解更多我为什么需要这个,我去了进一步的文档,我在这里分享,因为它可以帮助他人,就像他们帮助我一样。
用户提示包含应用程序的Info.plist文件中NSLocationWhenInUseUsageDescription键的文本,并且在调用此方法时需要存在该键。