iOS权限汇总

一、引入头文件

import Photos

import Contacts

import EventKit

import CoreTelephony

import HealthKit

二、枚举定义

enum XJAuthType: String {

    

    // MARK: - 隐私

    

    // 相机

    case camera = "相机"

    // 麦克风

    case microphone = "麦克风"

    // 照片

    case photo = "照片"

    // 位置

    case location = "位置"

    // 通讯录

    case addressbook = "通讯录"

    // 日历

    case event = "日历"

    // 备忘录

    case reminder = "备忘录"

    

    // MARK: - 其他

    

    // 网络

    case network = "网络"

    // 健康

    case healthy = "健康"

    // 蓝牙 (在CBCentralManager代理里面监听)

    case bluetooth = "蓝牙"

}

三、权限管理类

// MARK: - 权限管理类

class XJAuthorizationTool: NSObject {

    

    // 定位管理类

    fileprivate static var locationManager = CLLocationManager()

    

    /// 检测权限是否开启

    /// - Parameter type: 隐私类型

    /// - Returns: 是否开启

    static func checkAuthorization(_ type: XJAuthType) -> Bool {

        var isStart: Bool = false

        switch type {

        case .camera:

            isStart = checkCamera()

        case .microphone:

            isStart = checkMicrophone()

        case .photo:

            isStart = checkPhoto()

        case .location:

            isStart = checkLocation()

        case .addressbook:

            isStart = checkAddressbook()

        case .event:

            isStart = checkEvent()

        case .reminder:

            isStart = checkReminder()

        case .network:

            isStart = checkNetwork()

        case .healthy:

            isStart = checkHealth()

        default:

            break

        }

        return isStart

    }

    

    static func requestAuthorization(_ type: XJAuthType) {

        switch type {

        case .camera:

            requestCamera()

        case .microphone:

            requestMicrophone()

        case .photo:

            requestPhoto()

        case .location:

            requestLocation()

        case .addressbook:

            requestAddressbook()

        case .event:

            requestEvent()

        case .reminder:

            requestReminder()

        case .network:

            requestNetwork()

        case .healthy:

            requestHealth()

        default:

            break

        }

    }

}

 

// MARK: - 权限请求

extension XJAuthorizationTool {

    

    /// 相机权限

    fileprivate static func requestCamera() {

        AVCaptureDevice.requestAccess(for: .video) { granted in

            if granted {

                print("授权成功")

            } else {

                print("授权失败")

            }

        }

    }

    

    /// 麦克风权限

    fileprivate static func requestMicrophone() {

        AVAudioSession.sharedInstance().requestRecordPermission { granted in

            if granted {

                print("授权成功")

            } else {

                print("授权失败")

            }

        }

    }

    

    /// 相册权限

    fileprivate static func requestPhoto() {

        PHPhotoLibrary.requestAuthorization { status in

            var granted = false

            if status == .authorized {

                granted = true

                print("授权成功")

            } else {

                print("授权失败")

            }

        }

    }

    

    /// 定位权限

    fileprivate static func requestLocation() {

        self.locationManager.requestWhenInUseAuthorization()

    }

    

    /// 通讯录权限

    fileprivate static func requestAddressbook() {

        CNContactStore().requestAccess(for: .contacts) { granted, error in

            if error == nil {

                if granted {

                    print("授权成功")

                } else {

                    print("授权失败")

                }

            } else {

                

            }

        }

    }

    

    /// 日历权限

    fileprivate static func requestEvent() {

        EKEventStore().requestAccess(to: .event) { granted, error in

            if error == nil {

                if granted {

                    print("授权成功")

                } else {

                    print("授权失败")

                }

            } else {

                

            }

        }

    }

    

    /// 备忘录权限

    fileprivate static func requestReminder() {

        EKEventStore().requestAccess(to: .reminder) { granted, error in

            if error == nil {

                if granted {

                    print("授权成功")

                } else {

                    print("授权失败")

                }

            } else {

                

            }

        }

    }

    

    /// 联网权限

    fileprivate static func requestNetwork() {

        

    }

    

    /// 健康权限

    fileprivate static func requestHealth() {

        

        let shareObjectTypes: Set<HKSampleType> = [HKObjectType.quantityType(forIdentifier: .bodyMass)!,

                                                  HKObjectType.quantityType(forIdentifier: .height)!,

                                                  HKObjectType.quantityType(forIdentifier: .bodyMassIndex)!]

        

        let readObjectTypes: Set<HKObjectType> = [HKObjectType.characteristicType(forIdentifier: .dateOfBirth)!,

                                                  HKObjectType.characteristicType(forIdentifier: .biologicalSex)!,

                                                  HKObjectType.quantityType(forIdentifier: .stepCount)!]

        

        HKHealthStore().requestAuthorization(toShare: shareObjectTypes, read: readObjectTypes) { granted, error in

            if error == nil {

                if granted {

                    print("授权成功")

                } else {

                    print("授权失败")

                }

            } else {

                

            }

        }

    }

}

 

// MARK: - 权限检查

extension XJAuthorizationTool {

    

    // 检查摄像头和麦克风权限

    static func cameraAndmicrophone() -> Bool {

        return checkCamera() && checkMicrophone()

    }

    

    /// 相机权限

    fileprivate static func checkCamera() -> Bool {

        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)

        if authStatus != .restricted && authStatus != .denied {

            return true

        } else {

            showSettingAlert(.camera)

            return false

        }

    }

    

    /// 麦克风权限

    fileprivate static func checkMicrophone() -> Bool {

        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio)

        if authStatus != .restricted && authStatus != .denied {

            return true

        } else {

            showSettingAlert(.microphone)

            return false

        }

    }

    

    /// 相册权限

    fileprivate static func checkPhoto() -> Bool {

        let authStatus = PHPhotoLibrary.authorizationStatus()

        if authStatus != .restricted && authStatus != .denied {

            return true

        } else {

            showSettingAlert(.photo)

            return false

        }

    }

    

    /// 定位权限

    fileprivate static func checkLocation() -> Bool {

        let authStatus = CLLocationManager.authorizationStatus()

        if authStatus != .restricted && authStatus != .denied {

            return true

        } else {

            showSettingAlert(.location)

            return false

        }

    }

    

    /// 通讯录权限

    fileprivate static func checkAddressbook() -> Bool {

        let authStatus = CNContactStore.authorizationStatus(for: .contacts)

        if authStatus != .restricted && authStatus != .denied {

            return true

        } else {

            showSettingAlert(.addressbook)

            return false

        }

    }

 

    /// 日历权限

    fileprivate static func checkEvent() -> Bool {

        let authStatus = EKEventStore.authorizationStatus(for: .event)

        if authStatus != .restricted && authStatus != .denied {

            return true

        } else {

            showSettingAlert(.event)

            return false

        }

    }

    

    /// 备忘录权限

    fileprivate static func checkReminder() -> Bool {

        let authStatus = EKEventStore.authorizationStatus(for: .reminder)

        if authStatus != .restricted && authStatus != .denied {

            return true

        } else {

            showSettingAlert(.reminder)

            return false

        }

    }

    

    /// 健康权限

    fileprivate static func checkHealth() -> Bool {

        let healthStore = HKHealthStore()

        let hkObjectType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!

        let authStatus = healthStore.authorizationStatus(for: hkObjectType)

        if authStatus != .sharingDenied {

            return true

        } else {

            showHealthAlert()

            return false

        }

    }

    

    /// 联网权限

    fileprivate static func checkNetwork() -> Bool {

        let cellularData = CTCellularData()

        let authStatus = cellularData.restrictedState

        if authStatus != .restricted {

            return true

        } else {

            showNetworkAlert()

            return false

        }

    }

}

 

 

extension XJAuthorizationTool {

    /// 提示隐私

    static func showSettingAlert(_ type: XJAuthType) {

        let alertVC = UIAlertController.CreateAlertView(title: "您没有\(type.rawValue)权限", msgStr: "请到设置->隐私->\(type.rawValue),打开访问权限", cancelBtn_Title: "取消", sureBtn_Title: "设置") { (action) in

            let settingUrl = URL(string: UIApplication.openSettingsURLString)

            if let url = settingUrl, UIApplication.shared.canOpenURL(url) {

                UIApplication.shared.open(url, options: [:], completionHandler: nil)

            }

        }

        DispatchQueue.main.async {

            UIApplication.xj.topViewController()?.present(alertVC, animated: true, completion: nil)

        }

    }

    

    /// 提示联网权限

    static func showNetworkAlert() {

        let alertVC = UIAlertController.CreateAlertView(title: "您没有联网权限", msgStr: "请到设置->无线局域网或者蜂窝网络,进行设置", cancelBtn_Title: "取消", sureBtn_Title: "设置") { (action) in

            let settingUrl = URL(string: UIApplication.openSettingsURLString)

            if let url = settingUrl, UIApplication.shared.canOpenURL(url) {

                UIApplication.shared.open(url, options: [:], completionHandler: nil)

            }

        }

        DispatchQueue.main.async {

            UIApplication.xj.topViewController()?.present(alertVC, animated: true, completion: nil)

        }

    }

    

    /// 提示健康

    static func showHealthAlert() {

        let alertVC = UIAlertController.CreateAlertView(title: "您没有健康权限", msgStr: "请到设置->健康,进行设置", cancelBtn_Title: "取消", sureBtn_Title: "设置") { (action) in

            let settingUrl = URL(string: UIApplication.openSettingsURLString)

            if let url = settingUrl, UIApplication.shared.canOpenURL(url) {

                UIApplication.shared.open(url, options: [:], completionHandler: nil)

            }

        }

        DispatchQueue.main.async {

            UIApplication.xj.topViewController()?.present(alertVC, animated: true, completion: nil)

        }

    }

}

 

 

参考资源链接

https://www.csdn.net/tags/NtzaYgzsMDY1MTYtYmxvZwO0O0OO0O0O.html

判断权限开启状态

https://www.jianshu.com/p/4d72b82301e1

主动请求权限

https://www.jianshu.com/p/4ffdd86bd93c

posted @ 2022-06-14 15:24  HEJJY  阅读(472)  评论(0编辑  收藏  举报