我想在从服务器收到推送通知时发送位置详细信息。但 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/