首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在swift中即时处理位置权限

在swift中即时处理位置权限
EN

Stack Overflow用户
提问于 2015-06-19 16:34:35
回答 1查看 20.7K关注 0票数 17

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

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

代码语言:javascript
复制
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时,能够抓取当前位置并将其添加到地图中。我如何才能做到这一点?我有以下添加引脚的方法:

代码语言:javascript
复制
func addPin(location2D: CLLocationCoordinate2D){
    self.mapView.delegate = self
    var newPoint = MKPointAnnotation()
    newPoint.coordinate = location2D
    self.mapView.addAnnotation(newPoint)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-19 17:27:03

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

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

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

代码语言:javascript
复制
class myCoolClass: CLLocationManagerDelegate {
    var locManager: CLLocationManager!

    override func viewDidLoad() {
        locManager = CLLocationManager()
        locManager.delegate = self
    }
 }

最后,在您之前声明的类的主体中实现locationManager(_ didChangeAuthorizationStatus _)方法,当授权的状态发生更改时将调用此方法,因此只要您的用户单击该按钮。您可以像这样实现它:

代码语言:javascript
复制
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)。

这样你就可以处理每一种情况,无论用户只是给予了它的许可还是撤销了它。

票数 41
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30933593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档