Swift调用系统自带相机


本文自作自用笔记,不喜勿喷,诚谢纠错。

调用相机首先需要设置info.plist文件获取相机访问权限。http://www.cnblogs.com/lc901221/p/6599644.html

调用时需要遵守两个协议UIImagePickerControllerDelegate和UINavigationControllerDelegate。

下面贴出调用相机的代码:

     let imagePickerUIImagePickerController()

        //检测相机是否可用

        let isAvailable = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)

        //必须首先设置sourceType 然后再设置其他属性 否则会出异常,提示sourceType 必须是 UIImagePickerControllerSourceTypeCamera

        imagePicker.sourceType = .photoLibrary

        if isAvailable {

            imagePicker.sourceType = .camera

            //如果有前置摄像头则调用前置摄像头

            imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.front

            //是否显示控制栏,这里选择false会展示系统相机UI,如果要自定义可以将其隐藏

            imagePicker.showsCameraControls=false

        }

        //代理

        imagePicker.delegate = self

        //打开相机

        present(imagePicker, animated: true,  completion: {

        })

        //是否可编辑

        imagePicker.allowsEditing=false

下面是比较有用的两个协议方法:

  //获取当前相机拍摄的照片,确定时的回调

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

        self.dismiss(animated: true, completion: nil)

        if let photo = info[UIImagePickerControllerOriginalImage] as! UIImage?{

            let image = UIImageView.init(frame: self.view.frame)

            self.view.addSubview(image)

            image.image = photo

        }

    }

  //点击系统自定义取消按钮的回调

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

        self.dismiss(animated: true, completion: nil)

    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM