ios - 在位置访问权限中按下允许按钮后如何执行操作?

标签 ios swift core-location

enter image description here

我正在制作一个使用 GPS 坐标的应用程序,在实现它之前,我们必须像上图一样征求用户的许可。

如果用户在该警报处点击“允许”,我想制作 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
        }

    }
}

我将在 View Controller 方法中使用该类,如下所示,尤其是 getPermission()

func getCoordinate() {


        let coordinateAuthorizationStatus = locationManager.getPermission()

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

    }

目前,如果第一次触发该权限... 用户点击“允许”或“不允许”CLAuthorizationStatus 将始终为 .notDetermined

所以 activateGPSToSearchCoordinate() 永远不会被触发。

所以我需要激活 activateGPSToSearchCoordinate() 只有在按下该警报的“允许”之后

如何解决这个问题?

最佳答案

阅读更多关于 CLLocationManagerDelegate 的信息,有成功和失败的委托(delegate)方法。

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) {
}

关于ios - 在位置访问权限中按下允许按钮后如何执行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49356755/

相关文章:

ios - 您如何使用 Alamofire 测试证书固定?

ios - PausesLocationUpdatesAutomatically 不起作用

ios - Foursquare 始终跟踪地理定位(即使它已关闭)

ios - 委托(delegate)仍然为零

ios - 如何为 UIImageView 设置特定大小

ios - 设计:iOS “Add to Home Screen”

当用户在 iPhone 设置中关闭和打开位置服务时,iOS 应用程序会自动重新启动

ios - Swift 中的 UIWebView : exc_bad_access

ios - 如何在 UITableView 或 UICollectionView 中使用变量 UIStackView?

ios - 从 View 中触发淡入淡出标签延迟确实加载而不是在上一个淡入淡出结束时