swift - OS X 保存位置权限

标签 swift macos cocoa location cllocationmanager

我正在获取用户的 GPS 位置,如下所示:

var manager:CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()

    manager = CLLocationManager()
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.startUpdatingLocation()
    //manager.requestAlwaysAuthorization()
    //manager.requestWhenInUseAuthorization()

}

func locationManager(manager:CLLocationManager, didUpdateLocations locations:    [AnyObject]) { // Updated to current array syntax [AnyObject] rather than  AnyObject[]
    println("locations = \(locations)")
}

os x 应用程序似乎不存在注释掉的函数。它仍然对我有用,所以没关系。

但是每次我运行代码时,它都会请求使用位置的权限。 是否可以将权限存储在某处,以便仅在第一次执行时询问?

最佳答案

引用Apple的documentation :

Call the authorizationStatus class method to get the current authorization status for your app.

If the authorization status is kCLAuthorizationStatusRestricted or kCLAuthorizationStatusDenied, your app is not permitted to use location services and you should abort your attempt to use them.

您在 OS X 上的代码应如下所示:

override func viewDidLoad() {
    super.viewDidLoad()

    let status = CLLocationManager.authorizationStatus()
    if status == .Restricted || status == .Denied {
        // User permission not given
        return
    }
    
    manager = CLLocationManager()
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.startUpdatingLocation()
}

权限由 Mac OS X 集中管理。第一次调用 startUpdatingLocation 时,它会请求权限,然后记住用户的决定。

关于swift - OS X 保存位置权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36034851/

相关文章:

ios - 在 Swift 中使用 hpple

swift - 如何在 iOS 10.3 上从 UIBarButtonItem.appearance() 中删除标题

ios - 快速将 UITableView 添加到 View Controller

cocoa - 自定义 Finder 'get info' 窗口?

macos - 在文本字段中自动完成 Twitter 用户名( cocoa )

javascript - 在 macOS 上写入 Node.js 中的 ~/Documents 文件夹?

cocoa - 将 NSTextView 限制为仅显示数字

swift - 线程1 : EXC_BAD_ACCESS (code=1, address = 0x38)

objective-c - MFSideMenu 全尺寸平移手势

objective-c - 如何将多个窗口组合在一起并将它们放置到屏幕上的特定位置?