迅速处理位置权限

use*_*025 16 location core-location mkmapview ios swift

我正在尝试实现基本地图视图,并将用户的当前位置作为注释添加到地图中.我已将requestwheninuse密钥添加到我的info.plist并导入了coreLocation.

在我的视图中控制器的加载方法,我有以下内容:

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
}
Run Code Online (Sandbox Code Playgroud)

我得到了提示.检索位置的权限.当这种情况发生时,我得到的是我的打印说没有获得位置,显然是因为这在用户有机会点击OK之前运行.如果我完成应用程序并返回,我可以检索位置并将其添加到地图中.但是,我希望当用户第一次点击OK然后能够获取当前位置并将其添加到地图然后.我怎样才能做到这一点?我有以下添加引脚的方法:

func addPin(location2D: CLLocationCoordinate2D){
    self.mapView.delegate = self
    var newPoint = MKPointAnnotation()
    newPoint.coordinate = location2D
    self.mapView.addAnnotation(newPoint)
}
Run Code Online (Sandbox Code Playgroud)

The*_*Tom 38

为此,您需要为初始化didChangeAuthorizationStatus后不久调用的位置管理器委托实现该方法CLLocationManager.

首先,在文件的顶部不要忘记添加: import CoreLocation

为此,在您使用该位置的类中,添加委托协议.然后在该viewDidLoad方法中(或者applicationDidFinishLaunching如果您在AppDelegate)中初始化您的位置管理器并将其delegate属性设置为self:

class myCoolClass: CLLocationManagerDelegate {
    var locManager: CLLocationManager!

    override func viewDidLoad() {
        locManager = CLLocationManager()
        locManager.delegate = self
    }
 }
Run Code Online (Sandbox Code Playgroud)

最后,在您之前声明的类的主体中实现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
    }
}
Run Code Online (Sandbox Code Playgroud)

Swift 4 - 新的枚举语法

对于Swift 4,只需将每个枚举案例的第一个字母切换为小写(.notDetermined,.authorizedWhenInUse,.authorizedAlways,.restricted和.denied)

这样你就可以处理每一个案例,用户只是给予了许可或撤销了它.