迅速处理位置权限
我正在尝试实现基本地图视图,并将用户的当前位置作为注释添加到地图中。 我已将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 }
我得到了提示。 检索位置的权限。 随着这种情况的发生,我得到的是我的打印说没有获得位置,显然是因为这在用户有机会点击OK之前运行。 如果我完成应用程序并返回,我可以检索位置并将其添加到地图中。 但是,我希望当用户第一次点击OK然后能够抓住当前位置并将其添加到地图然后。 我怎样才能做到这一点? 我有以下添加引脚的方法:
func addPin(location2D: CLLocationCoordinate2D){ self.mapView.delegate = self var newPoint = MKPointAnnotation() newPoint.coordinate = location2D self.mapView.addAnnotation(newPoint) }
为此,您需要为CLLocationManager
初始化后不久调用的位置管理器委托实现方法didChangeAuthorizationStatus
。
首先,在文件的顶部不要忘记添加: import CoreLocation
为此,在您使用该位置的类中,添加委托协议。 然后在viewDidLoad
方法(或AppDelegate
如果你在AppDelegate
)初始化你的位置管理器并将其delegate
属性设置为self
:
class myCoolClass: CLLocationManagerDelegate { var locManager: CLLocationManager! override func viewDidLoad() { locManager = CLLocationManager() locManager.delegate = self } }
最后,在您之前声明的类的主体中实现locationManager(_ didChangeAuthorizationStatus _)方法,当授权的状态发生更改时,将调用此方法,以便用户单击该按钮。 您可以像这样实现它:
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 eg 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)
这样你就可以处理每一个案例,用户只是给予了许可或撤销了它。