用到了记录下.
须先在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!()
}
}
}