我正在制作一个使用 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/