首页 > 解决方案 > SwiftUI 位置权限不显示

问题描述

我正在尝试检查我的应用程序的位置权限,但该应用程序未显示包含“始终”、“仅在使用该应用程序时”或“从不”等所有选项的弹出窗口

单击如下按钮时,我正在这样做:

Button(action: {
                LocationManager.shared.requestLocationAuthorization()
                print("click to current" + searchText)
               }) {
               Text("Current Location)
            }

然后我使用下面的类:

class LocationManager: NSObject, CLLocationManagerDelegate {

    static let shared = LocationManager()
    private var locationManager: CLLocationManager = CLLocationManager()
    private var requestLocationAuthorizationCallback: ((CLAuthorizationStatus) -> Void)?

    public func requestLocationAuthorization() {
        self.locationManager.delegate = self
        let currentStatus = CLLocationManager.authorizationStatus()

        // Only ask authorization if it was never asked before
        guard currentStatus == .notDetermined else { return }

        if #available(iOS 13.4, *) {
            self.requestLocationAuthorizationCallback = { status in
                if status == .authorizedWhenInUse {
                    self.locationManager.requestAlwaysAuthorization()
                }
            }
            self.locationManager.requestWhenInUseAuthorization()
        } else {
            self.locationManager.requestAlwaysAuthorization()
        }
    }
    public func locationManager(_ manager: CLLocationManager,
                                didChangeAuthorization status: CLAuthorizationStatus) {
        self.requestLocationAuthorizationCallback?(status)
    }
}

无论我在做什么,询问用户的弹出窗口都不会弹出。

该按钮在 VStack 中被调用。

谢谢你的帮助

标签: iosswiftiphoneswiftui

解决方案


您的 info.plist 中的键是否正确?

<key>NSLocationUsageDescription</key>
<string>Your description here</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Your description here</string>

根据 Apple 的说法,如果这些键丢失。

重要您必须将所需的密钥添加到应用的 Info.plist 文件中。如果所需的密钥不存在,授权请求将立即失败。

来源:https ://developer.apple.com/documentation/corelocation/requesting_authorization_for_location_services


推荐阅读