Swift-常用权限检测

1.选择导入头文件

import Photos
import AssetsLibrary
import MediaPlayer
import CoreTelephony
import CoreLocation
import AVFoundation

1.是否开启媒体资料库/Apple Music 服务

/// 是否开启媒体资料库/Apple Music 服务 需要iOS9.3之后可使用
@available(iOS 9.3, *)
func openMediaPlayerServiceWithBlock(action :@escaping ((Bool)->())) {
    let authStatus = MPMediaLibrary.authorizationStatus()
    if authStatus == MPMediaLibraryAuthorizationStatus.notDetermined {
        MPMediaLibrary.requestAuthorization { (status) in
            if (status == MPMediaLibraryAuthorizationStatus.authorized) {
                DispatchQueue.main.async {
                    action(true)
                }
            }else{
                DispatchQueue.main.async {
                    action(false)
                }
            }
        }
    } else if authStatus == MPMediaLibraryAuthorizationStatus.authorized {
        action(true)
    } else {
        action(false)
    }
}

2.检测是否开启联网

/// 检测是否开启联网
func hw_openEventServiceWithBolck(action :@escaping ((Bool)->())) {
    let cellularData = CTCellularData()
    cellularData.cellularDataRestrictionDidUpdateNotifier = { (state) in
        if state == CTCellularDataRestrictedState.restrictedStateUnknown ||  state == CTCellularDataRestrictedState.notRestricted {
            action(false)
        } else {
            action(true)
        }
    }
    let state = cellularData.restrictedState
    if state == CTCellularDataRestrictedState.restrictedStateUnknown ||  state == CTCellularDataRestrictedState.notRestricted {
        action(false)
    } else {
        action(true)
    }
}

3.检测是否开启定位

/// 检测是否开启定位
func hw_openLocationServiceWithBlock(action :@escaping ((Bool)->())) {
    var isOpen = false
    if CLLocationManager.locationServicesEnabled() || CLLocationManager.authorizationStatus() != .denied {
        isOpen = true
    }
    action(isOpen)
}

4.检测是否开启摄像头

/// 检测是否开启摄像头
func hw_openCaptureDeviceServiceWithBlock(action :@escaping ((Bool)->())) {
    let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
    if authStatus == AVAuthorizationStatus.notDetermined {
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (granted) in
            action(granted)
        }
    } else if authStatus == AVAuthorizationStatus.restricted || authStatus == AVAuthorizationStatus.denied {
        action(false)
    } else {
        action(true)
    }
}

5.检测是否开启相册

/// 检测是否开启相册
func hw_openAlbumServiceWithBlock(action :@escaping ((Bool)->())) {
    var isOpen = true
    let authStatus = PHPhotoLibrary.authorizationStatus()
    if authStatus == PHAuthorizationStatus.restricted || authStatus == PHAuthorizationStatus.denied {
        isOpen = false;
    }
    action(isOpen)
}

6.检测是否开启麦克风

/// 检测是否开启麦克风
func hw_openRecordServiceWithBlock(action :@escaping ((Bool)->())) {
    let permissionStatus = AVAudioSession.sharedInstance().recordPermission()
    if permissionStatus == AVAudioSessionRecordPermission.undetermined {
        AVAudioSession.sharedInstance().requestRecordPermission { (granted) in
            action(granted)
        }
    } else if permissionStatus == AVAudioSessionRecordPermission.denied {
        action(false)
    } else {
        action(true)
    }
}

7.跳转系统设置界面

// MARK: - 跳转系统设置界面
func hw_OpenURL() {
    let url = URL(string: UIApplicationOpenSettingsURLString)
    let alertController = UIAlertController(title: "访问受限",
                                            message: "点击“设置”,允许访问权限",
                                            preferredStyle: .alert)
    let cancelAction = UIAlertAction(title:"取消", style: .cancel, handler:nil)
    let settingsAction = UIAlertAction(title:"设置", style: .default, handler: {
        (action) -> Void in
        if  UIApplication.shared.canOpenURL(url!) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url!, options: [:],completionHandler: {(success) in})
            } else {
                UIApplication.shared.openURL(url!)
            }
        }
    })
    alertController.addAction(cancelAction)
    alertController.addAction(settingsAction)
    UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
}

Dome

代码更新(新增isSet == true快速跳转提示)

注意可以直接复制 不影响以前使用
修复定位权限检测不准


import Photos
import AssetsLibrary
import MediaPlayer
import CoreTelephony
import CoreLocation
import AVFoundation




enum HWpermissionsType{
    /// 相机
    case camera
    /// 相册
    case photo
    /// 位置
    case location
    /// 网络
    case network
    /// 麦克风
    case microphone
    /// 媒体库
    case media
}

// MARK: - 开启媒体资料库/Apple Music 服务
/// 开启媒体资料库/Apple Music 服务
@available(iOS 9.3, *)
func hw_openMediaPlayerServiceWithBlock(_ isSet:Bool? = nil,_ action :@escaping ((Bool)->())) {
    let authStatus = MPMediaLibrary.authorizationStatus()
    if authStatus == MPMediaLibraryAuthorizationStatus.notDetermined {
        MPMediaLibrary.requestAuthorization { (status) in
            if (status == MPMediaLibraryAuthorizationStatus.authorized) {
                DispatchQueue.main.async {
                    action(true)
                }
            }else{
                DispatchQueue.main.async {
                    action(false)
                     if isSet == true {hw_OpenURL(.media)}
                }
            }
        }
    } else if authStatus == MPMediaLibraryAuthorizationStatus.authorized {
        action(true)
    } else {
        action(false)
         if isSet == true {hw_OpenURL(.media)}
    }
}

// MARK: - 检测是否开启联网
/// 检测是否开启联网
func hw_openEventServiceWithBolck(_ isSet:Bool? = nil,_ action :@escaping ((Bool)->())) {
    let cellularData = CTCellularData()
    cellularData.cellularDataRestrictionDidUpdateNotifier = { (state) in
        if state == CTCellularDataRestrictedState.restrictedStateUnknown ||  state == CTCellularDataRestrictedState.notRestricted {
            action(false)
            if isSet == true {hw_OpenURL(.network)}
        } else {
            action(true)
        }
    }
    let state = cellularData.restrictedState
    if state == CTCellularDataRestrictedState.restrictedStateUnknown ||  state == CTCellularDataRestrictedState.notRestricted {
        action(false)
        if isSet == true {hw_OpenURL(.network)}
    } else {
        action(true)
    }
}

// MARK: - 检测是否开启定位
/// 检测是否开启定位
func hw_openLocationServiceWithBlock(_ isSet:Bool? = nil,_ action :@escaping ((Bool)->())) {
    var isOpen = false
//    if CLLocationManager.locationServicesEnabled() || CLLocationManager.authorizationStatus() != .denied {
//        isOpen = true
//    }
    if CLLocationManager.authorizationStatus() != .restricted && CLLocationManager.authorizationStatus() != .denied {
        isOpen = true
    }
    if isOpen == false && isSet == true {hw_OpenURL(.location)}
    action(isOpen)
}

// MARK: - 检测是否开启摄像头
/// 检测是否开启摄像头 (可用)
func hw_openCaptureDeviceServiceWithBlock(_ isSet:Bool? = nil,_ action :@escaping ((Bool)->())) {
    let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
    if authStatus == AVAuthorizationStatus.notDetermined {
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (granted) in
            action(granted)
            if granted == false && isSet == true {hw_OpenURL(.camera)}
        }
    } else if authStatus == AVAuthorizationStatus.restricted || authStatus == AVAuthorizationStatus.denied {
        action(false)
        if isSet == true {hw_OpenURL(.camera)}
    } else {
        action(true)
    }
}
// MARK: - 检测是否开启相册
/// 检测是否开启相册
func hw_openAlbumServiceWithBlock(_ isSet:Bool? = nil,_ action :@escaping ((Bool)->())) {
    var isOpen = true
    let authStatus = PHPhotoLibrary.authorizationStatus()
    if authStatus == PHAuthorizationStatus.restricted || authStatus == PHAuthorizationStatus.denied {
        isOpen = false;
        if isSet == true {hw_OpenURL(.photo)}
    }
    action(isOpen)
}

// MARK: - 检测是否开启麦克风
/// 检测是否开启麦克风
func hw_openRecordServiceWithBlock(_ isSet:Bool? = nil,_ action :@escaping ((Bool)->())) {
    let permissionStatus = AVAudioSession.sharedInstance().recordPermission()
    if permissionStatus == AVAudioSessionRecordPermission.undetermined {
        AVAudioSession.sharedInstance().requestRecordPermission { (granted) in
            action(granted)
            if granted == false && isSet == true {hw_OpenURL(.microphone)}
        }
    } else if permissionStatus == AVAudioSessionRecordPermission.denied || permissionStatus == AVAudioSessionRecordPermission.undetermined{
        action(false)
        if isSet == true {hw_OpenURL(.microphone)}
    } else {
        action(true)
    }
}
// MARK: - 跳转系统设置界面
func hw_OpenURL(_ type: HWpermissionsType? = nil) {
    let title = "访问受限"
    var message = "请点击“前往”,允许访问权限"
    let appName: String = (Bundle.main.infoDictionary!["CFBundleDisplayName"] ?? "") as! String //App 名称
    if type == .camera { // 相机
        message = "请在iPhone的\"设置-隐私-相机\"选项中,允许\"\(appName)\"访问你的相机"
    } else if type == .photo { // 相册
        message = "请在iPhone的\"设置-隐私-照片\"选项中,允许\"\(appName)\"访问您的相册"
    } else if type == .location { // 位置
        message = "请在iPhone的\"设置-隐私-定位服务\"选项中,允许\"\(appName)\"访问您的位置,获得更多商品信息"
    } else if type == .network { // 网络
        message = "请在iPhone的\"设置-蜂窝移动网络\"选项中,允许\"\(appName)\"访问您的移动网络"
    } else if type == .microphone { // 麦克风
        message = "请在iPhone的\"设置-隐私-麦克风\"选项中,允许\"\(appName)\"访问您的麦克风"
    } else if type == .media { // 媒体库
        message = "请在iPhone的\"设置-隐私-媒体与Apple Music\"选项中,允许\"\(appName)\"访问您的媒体库"
    }
    let url = URL(string: UIApplicationOpenSettingsURLString)
    let alertController = UIAlertController(title: title,
                                            message: message,
                                            preferredStyle: .alert)
    let cancelAction = UIAlertAction(title:"取消", style: .cancel, handler:nil)
    let settingsAction = UIAlertAction(title:"前往", style: .default, handler: {
        (action) -> Void in
        if  UIApplication.shared.canOpenURL(url!) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url!, options: [:],completionHandler: {(success) in})
            } else {
                UIApplication.shared.openURL(url!)
            }
        }
    })
    alertController.addAction(cancelAction)
    alertController.addAction(settingsAction)
    UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,033评论 3 119
  • 孤陋寡闻,加入007以前,虽然听说过比特币,但对区块链以及币圈一无所知,当一场作业雨后,七耳们写的关于此领...
    燧石取火阅读 5,120评论 4 4
  • 大风吹,在夜幕降临的时刻 一个人走出阴影,跨过山河 夕阳余晖渐渐沉寂,光碎满地 近不见暖阳,似乎寒冬尚未离去 似乎...
    闲狐兔阅读 2,498评论 0 1
  • 缠绕画 圈,圈,圈……变成了美丽花朵。
    人生若只如初16阅读 1,157评论 0 0
  • 高淑娟,三十多点吧。十几年前的她,不善言辞,很少与人交谈。 中间有八年没共事,现在再看她,变化不小,话多了,话题总...
    三门峡752蔡淑棉阅读 2,463评论 6 5