swift - macos CLLocationManager 提示

标签 swift macos core-location cllocationmanager

我想在从服务器收到推送通知时发送位置详细信息。但 Macos 应用程序在启动时不会询问位置权限。在 info.plist 中添加了所有隐私项。它在调用locationmanager.startUpdatingLocation()时请求许可。如果我取消它,则不再询问。代码如下。

class AppDelegate: NSObject, NSApplicationDelegate, CLLocationManagerDelegate {
  let locationManager = CLLocationManager()
  func applicationDidFinishLaunching(_ aNotification: Notification) {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
  }
 func scanLocationRequest{
   locationManager.startUpdatingLocation()
   // Call this when a notification receives.
 }
 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let currentLocation = locations.last
    locationManager.stopUpdatingLocation()
    sendLocationReport(currentLocation: currentLocation!)
 }

}

最佳答案

要检查用户是否具有位置访问权限,请使用以下代码:

var isPermissionAvailable: Bool {
    let status = CLLocationManager.authorizationStatus()
    switch status {
    case .authorizedAlways, .authorizedWhenInUse:
        return true
    case .denied, .restricted, .notDetermined:
        requestForLocation()
        return false
    }
}

func requestForLocation() {

    // Edit
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
}

要在应用程序启动时显示弹出窗口,您可以在 AppDelegate 类的 applicationDidFinishLaunching(_ aNotification:) 中使用以下代码:

if isPermissionAvailable {
    // Do your work on permission available
}

关于swift - macos CLLocationManager 提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54196447/

相关文章:

swift - UILabel 不会更新以显示获取的位置坐标

swift - 为什么在这种情况下非可选函数可以返回 nil?

macos - 将 XInput 调用转换为 MAC OS X 上的 DirectInput 调用(从 PS3 模拟 x360 Controller )

ruby - 在 macrubyc 中使用 --static 选项时出错

r - 为什么 Rpy2 没有安装在我的 OSX Sierra 终端中?

iphone - 需要帮助来提高纬度和经度的准确性

ios - 每5分钟获取后台位置更新一次

ios - 手动创建的 UIWindow 大小错误

ios - 为 .xib View 设置 ViewController

google-maps-api-3 - 快速使用未解析的标识符 'GMServices'