ios - 在位置访问权限中按下允许按钮后如何执行 Action ?-LMLPHP
我正在制作一个应用程序,使用坐标从全球定位系统,在实施它之前,我们必须征求用户的许可,如上图所示。
我想让用户点击“允许”,然后触发activateGPSToSearchCoordinate(),但如果点击“不允许”,我不想做任何事情。
这是我现在的代码,它不能正常工作

class LocationManager: NSObject {
    let manager = CLLocationManager()
    var didGetLocation: ((Coordinate?) -> Void)?

    override init() {
        super.init()

        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestLocation()
    }

    func getPermission() -> CLAuthorizationStatus {
        // to ask permission to the user by showing an alert (the alert message is available on info.plist)

        if CLLocationManager.authorizationStatus() == .notDetermined {
            manager.requestWhenInUseAuthorization()
            return .notDetermined
        } else if CLLocationManager.authorizationStatus() == .denied {
            return .denied
        } else if CLLocationManager.authorizationStatus() == .authorizedWhenInUse  {
            return .authorizedWhenInUse
        } else {
            return .notDetermined
        }

    }
}

我将在下面这样的视图控制器方法中使用该类,特别是getPermission()
func getCoordinate() {


        let coordinateAuthorizationStatus = locationManager.getPermission()

        if coordinateAuthorizationStatus == .authorizedWhenInUse {
            activateGPSToSearchCoordinate()
        } else if coordinateAuthorizationStatus == .denied {
            showAlertSetting()
        }

    }

目前,如果第一次触发该权限。。。
用户点击“允许”或“不允许”CLAuthorizationStatus将始终.notDetermined
因此,activateGPSToSearchCoordinate()永远不会被触发。
所以我需要在按下警报的“允许”后激活activateGPSToSearchCoordinate()
如何解决这个问题?

最佳答案

了解更多关于CLLocationManagerDelegate的信息,有成功和失败的委托方法。

public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    GlobalObjects.shared.latitude  = locations[0].coordinate.latitude
    GlobalObjects.shared.longtitude = locations[0].coordinate.longitude
    GlobalObjects.shared.locationOBJ = locations[0]
    print(GlobalObjects.shared.latitude, GlobalObjects.shared.longtitude)
}

public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
}

10-07 19:49
查看更多