iOS Developer

swift相册相机权限处理

2017-10-27  本文已影响1076人  hello老文

用到了记录下.

须先在info.plist中添加两个keyNSPhotoLibraryUsageDescription, 和NSCameraUsageDescription, 内容填提示内容.

相机

// 使用
self.cameraPermissions(authorizedBlock: {
    print("打开相机")
}, deniedBlock: {
    print("没有权限使用相机")
})

// 相机权限
class func cameraPermissions(authorizedBlock: OperationBlock?, deniedBlock: OperationBlock?) {
    let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
    
    // .notDetermined  .authorized  .restricted  .denied
    if authStatus == .notDetermined {
        // 第一次触发授权 alert
        AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in
            self.cameraPermissions(authorizedBlock: authorizedBlock, deniedBlock: deniedBlock)
        })
    } else if authStatus == .authorized {
        if authorizedBlock != nil {
            authorizedBlock!()
        }
    } else {
        if deniedBlock != nil {
            deniedBlock!()
        }
    }
}

相册

iOS9.0后ALAssetsLibrary过时了, 换成使用PHPhotoLibrary

// 使用
self.photoAlbumPermissions(authorizedBlock: {
    print("打开相册")
}, deniedBlock: {
    print("没有权限打开相册")
})

// 相册权限
class func photoAlbumPermissions(authorizedBlock: OperationBlock?, deniedBlock: OperationBlock?) {
    let authStatus = PHPhotoLibrary.authorizationStatus()
    
    // .notDetermined  .authorized  .restricted  .denied
    if authStatus == .notDetermined {
        // 第一次触发授权 alert
        PHPhotoLibrary.requestAuthorization { (status:PHAuthorizationStatus) -> Void in
            self.photoAlbumPermissions(authorizedBlock: authorizedBlock, deniedBlock: deniedBlock)
        }
    } else if authStatus == .authorized  {
        if authorizedBlock != nil {
            authorizedBlock!()
        }
    } else {
        if deniedBlock != nil {
            deniedBlock!()
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读