我在模拟器上遇到一个关于位置授权的奇怪问题,希望大家能帮我分析一下。
问题描述:
- 我的 App 在模拟器上首次运行时,会请求位置权限。
- 我选择“拒绝”授权。
- 然后,我通过模拟器的“设置” -> “隐私与安全性” -> “位置服务”中,开启了位置权限。
- 但是,当我返回 App 时,CLLocationManager.authorizationStatus 始终返回 .notDetermined,并且无法再次弹出授权请求弹窗。
- 即使我多次重置模拟器设置,问题依然存在。
import CoreLocation
@Observable
final class LocationManager: NSObject, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var currentLocation: CLLocationCoordinate2D?
override init() {
super.init()
locationManager.delegate = self
}
// 位置权限发生变化时被调用
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
let status = manager.authorizationStatus
print("Authorize Status: \(status)")
switch status {
case .authorizedWhenInUse, .authorizedAlways:
locationManager.startUpdatingLocation() // 开始更新位置
case .denied, .restricted:
stopLocation() // 停止位置更新
case .notDetermined:
// 如果用户未做出选择,尝试请求权限
locationManager.requestWhenInUseAuthorization() // 请求位置权限
print("Location permission not determined.")
@unknown default:
break
}
}
// 单次请求位置
func requestLocation() {
let status = locationManager.authorizationStatus
if status == .authorizedWhenInUse || status == .authorizedAlways {
locationManager.requestLocation()
} else {
locationManager.requestWhenInUseAuthorization()
}
}
// 位置更新时被调用
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let newLocation = locations.first else { return }
currentLocation = newLocation.coordinate
print("Updated location: \(newLocation.coordinate)")
}
// 当位置更新失败时调用
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location update failed with error: \(error.localizedDescription)")
currentLocation = nil
// 在实际应用中,你可能需要通知调用者位置更新失败
}
// 停止位置更新
func stopLocation() {
locationManager.stopUpdatingLocation()
print("Stopped updating location")
}
}