swift相机启动

来源:互联网 发布:润和软件 死人 编辑:程序博客网 时间:2024/06/07 10:23

1.在info.plist中添加参数

Privacy - Camera Usage Description   允许使用相机

Privacy - Photo Library Usage Description  允许使用图库


2.代码  

注意:类要继承 

UIImagePickerControllerDelegate

/**

     判断相机权限

     

     - returns: 有权限返回true,没权限返回false

     */

    func cameraPermissions() -> Bool{

        

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

        

        if(authStatus == AVAuthorizationStatus.denied || authStatus ==AVAuthorizationStatus.restricted) {

            return false

        }else {

            return true

        }

        

    }

// TODO: 调用相机拍照

    func PaiZhao(){

        if(self.cameraPermissions() ==true){

            let imagePicker = UIImagePickerController()

            //判断设备是否有相机

            ifUIImagePickerController.isSourceTypeAvailable(.camera){

                // 把UIImagePicker-Controller的委托属性设置为DetailViewController对象

                imagePicker.delegate = self

                // 调用摄像机

                imagePicker.sourceType = .camera

                // 以模态的的形式显示。其视图会占据整个屏幕

                self.present(imagePicker, animated:true, completion: nil)

            }else{

                CommonFunction.TanChuang(msg:"无法调用相机,联系管理员", uiview: self)

                // 让用户选择相册,重相册中选取一张照片

                //            imagePicker.sourceType = .photoLibrary

            }

        }else{

            //弹出提示框

            self.sheet =UIAlertController(title: nil, message: "请在设置中打开摄像头权限", preferredStyle: .alert)

            

            let tempAction = UIAlertAction(title: "确定", style: .cancel) { (action)in

            }

            self.sheet.addAction(tempAction)

            self.present(self.sheet, animated:true, completion: nil)

        }

    }

// TODO: 摄像机委托方法

    func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo info: [String :Any]) {

        // 重数据源中获取图片

        let image = info[UIImagePickerControllerOriginalImage]as! UIImage

        

        // 将图片保存内存当中

//        imageStore.setImage(image: image, forKey: item.itemKey)

        // 设置显示图片

        imageView.image = image

        

        // 关闭摄像机模态窗

        // 必须调用这种方法关闭

        dismiss(animated: true, completion: nil)

    }