这里的问题是,在 10.15 之前的 macOS 上,不会像在 iOS 上那样显式调用请求位置访问。调用时自动出现用户权限提示startUpdatingLocation()
.
在上面的代码中,执行永远不会到达该调用,因为您的函数startReceivingLocationChanges
始终在检查当前状态的第一个语句中返回(最有可能是“状态尚未确定”)。所以它永远不会到达startUpdatingLocation()
在该函数中进一步调用,因此永远不会提示用户允许位置报告。
在 macOS 10.15 中requestAlwaysAuthorization()
可用,但如果您只需要在使用应用程序时使用位置,则似乎不需要。
另外,在 macOS 上.authorized
似乎比.authorizedAlways
(记录为同义词),尽管添加了requestAlwaysAuthorization()
在 10.15 中,他们可能会更改此功能(尽管文档尚未更新以表明在回答此问题时已发生这种情况)。
如果你没有打电话requestAlwayAuthorization()
那么看来只有NSLocationWhenInUseUsageDescription
需要 info.plist 密钥。
此外,还需要为 macOS 应用程序项目在“签名和功能”下的“强化运行时”中设置“位置”复选框。这是我正在测试的 macOS 10.14.6 上的 Xcode 11.2.1 所必需的。较旧的设置或不采用强化运行时(现在是默认设置)的设置可能必须在项目构建设置中的不同位置进行设置。
以下是 NSViewController 子类的源代码,该子类在 macOS 10.14.6 上的 Xcode 11.2.1 中成功检查位置管理器和当前位置:
import Cocoa
import CoreLocation
class ViewController: NSViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
print("starting location update requests")
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
print("location manager auth status changed to:" )
switch status {
case .restricted:
print("status restricted")
case .denied:
print("status denied")
case .authorized:
print("status authorized")
let location = locationManager.location
print("location: \(String(describing: location))")
case .notDetermined:
print("status not yet determined")
default:
print("unknown state: \(status)")
}
}
func locationManager(_ manager: CLLocationManager,
didFailWithError error: Error) {
print( "location manager failed with error \(error)" )
}
}
这对我在 macOS 上有效如果我第一次启动应用程序时对“启用位置服务”提示说“是”.
控制台输出是(稍微混淆):
位置管理器身份验证状态更改为:状态尚未确定
位置管理器身份验证状态更改为:状态授权位置:
可选( +/- 65.00m (速度 -1.00 mps /
课程 -1.00) @ 2019 年 11 月 15 日上午 10:24:30 太平洋标准时间)
制作此样品的步骤:
- 打开 Xcode 并创建一个新的 macOS 项目
- 编辑项目模板提供的ViewController以匹配上面的代码
- Add the
NSLocationWhenInUseUsageDescription
info.plist 的关键
- 在项目设置中应用程序目标的“签名和功能”部分中,选中“强化运行时”下的“位置”复选框。