美文网首页iOS Developer
swift相册相机权限处理

swift相册相机权限处理

作者: hello老文 | 来源:发表于2017-10-27 17:25 被阅读1076次

    用到了记录下.

    须先在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!()
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:swift相册相机权限处理

        本文链接:https://www.haomeiwen.com/subject/cfrdpxtx.html