我正在尝试实现一个基本的地图视图,并将用户的当前位置作为注释添加到地图中。我已经向我的info.plist和导入的coreLocation添加了requestwheninuse密钥。
在我的视图控制器的did load方法中,我有以下内容:
locManager.requestWhenInUseAuthorization()
var currentLocation : CLLocation
if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse){
currentLocation = locManager.location
println("currentLocation is \(currentLocation)")
}
else{
println("not getting location")
// a default pin
}我正在得到提示符。检索位置的权限。当这种情况发生时,我得到的打印结果是not gets,显然是因为这是在用户点击OK之前运行的。如果我离开应用程序并回来,我可以检索位置并将其添加到地图中。然而,我希望当用户第一次点击OK时,能够抓取当前位置并将其添加到地图中。我如何才能做到这一点?我有以下添加引脚的方法:
func addPin(location2D: CLLocationCoordinate2D){
self.mapView.delegate = self
var newPoint = MKPointAnnotation()
newPoint.coordinate = location2D
self.mapView.addAnnotation(newPoint)
}发布于 2015-06-19 17:27:03
为此,您需要为在CLLocationManager初始化后不久调用的位置管理器委托实现方法didChangeAuthorizationStatus。
首先,不要忘了在文件的顶部添加:import CoreLocation
为此,请在使用位置的类中添加委托协议。然后在viewDidLoad方法中(如果在AppDelegate中,则为applicationDidFinishLaunching )初始化位置管理器,并将其delegate属性设置为self
class myCoolClass: CLLocationManagerDelegate {
var locManager: CLLocationManager!
override func viewDidLoad() {
locManager = CLLocationManager()
locManager.delegate = self
}
}最后,在您之前声明的类的主体中实现locationManager(_ didChangeAuthorizationStatus _)方法,当授权的状态发生更改时将调用此方法,因此只要您的用户单击该按钮。您可以像这样实现它:
private func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
// If status has not yet been determied, ask for authorization
manager.requestWhenInUseAuthorization()
break
case .authorizedWhenInUse:
// If authorized when in use
manager.startUpdatingLocation()
break
case .authorizedAlways:
// If always authorized
manager.startUpdatingLocation()
break
case .restricted:
// If restricted by e.g. parental controls. User can't enable Location Services
break
case .denied:
// If user denied your app access to Location Services, but can grant access from Settings.app
break
default:
break
}
}Swift 4-新的枚举语法
对于Swift 4,只需将每个枚举大小写的第一个字母切换为小写(.notDetermined、.authorizedWhenInUse、.authorizedAlways、.restricted和.denied)。
这样你就可以处理每一种情况,无论用户只是给予了它的许可还是撤销了它。
https://stackoverflow.com/questions/30933593
复制相似问题