在 iOS 14 上检查用户位置权限状态

Posted

技术标签:

【中文标题】在 iOS 14 上检查用户位置权限状态【英文标题】:Checking user location permission status on iOS 14 【发布时间】:2020-12-26 12:28:17 【问题描述】:

所以我想检查我是否可以访问 ios14 上的用户位置 & 我找到了这段代码,但 XCode(12) 用这个对我大喊:

'authorizationStatus()' was deprecated in iOS 14.0

这里是代码:

func hasLocationPermission() -> Bool 
       var hasPermission = false
       if CLLocationManager.locationServicesEnabled() 
           switch CLLocationManager.authorizationStatus()  // <= 'authorizationStatus()' was deprecated in iOS 14.0
           case .notDetermined, .restricted, .denied:
               hasPermission = false
           case .authorizedAlways, .authorizedWhenInUse:
               hasPermission = true
           @unknown default:
               hasPermission = false
             
        else 
            hasPermission = false
       
        return hasPermission

那我应该改用什么?

【问题讨论】:

developer.apple.com/documentation/corelocation/… 我无法理解苹果文档中的任何内容:| 你应该实现委托方法locationManagerDidChangeAuthorization并检查该方法中authorizationStatus的值 【参考方案1】:

在 iOS 14 中,'authorizationStatus()' 已被弃用:

https://developer.apple.com/documentation/corelocation/cllocationmanager/1423523-authorizationstatus

您应该改用 locationManagerDidChangeAuthorization:

func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) 

        switch manager.authorizationStatus 
            case .authorizedAlways , .authorizedWhenInUse:
                break
            case .notDetermined , .denied , .restricted:
                break
            default:
                break
        
        
        switch manager.accuracyAuthorization 
            case .fullAccuracy:
                break
            case .reducedAccuracy:
                break
            default:
                break
        

【讨论】:

locationManagerDidChangeAuthorization(_:) 仅适用于 iOS14。 developer.apple.com/documentation/corelocation/…【参考方案2】:

iOS 14 及更早版本

func locationAuthorizationStatus() -> CLAuthorizationStatus 
    let locationManager = CLLocationManager()
    var locationAuthorizationStatus : CLAuthorizationStatus
    if #available(iOS 14.0, *) 
        locationAuthorizationStatus =  locationManager.authorizationStatus
     else 
        // Fallback on earlier versions
        locationAuthorizationStatus = CLLocationManager.authorizationStatus()
    
    return locationAuthorizationStatus

【讨论】:

【参考方案3】:

iOS 14 检查用户是否允许

extension CLLocationManager 
    
    func checkLocationPermission() 
        
        if self.authorizationStatus != .authorizedWhenInUse && self.authorizationStatus != .authorizedAlways 
            
            self.requestAlwaysAuthorization()
            
        
        
    
    

使用

self.LocationManager.checkLocationPermission()

【讨论】:

以上是关于在 iOS 14 上检查用户位置权限状态的主要内容,如果未能解决你的问题,请参考以下文章

即使用户授予位置权限检查,三星 note 20 也总是会被拒绝

Objective C: iOS 14 如何做网络隐私权限检查

React Native iOS:检查通知权限内存泄漏,如何在应用启动时检查通知权限?

检查用户位置的权限

检查用户是不是在代号中接受了 iOS 中的推送通知权限

如何在swift UI Test下检查应用程序状态