美文网首页
iOS调用相机拍照或从相册选择照片

iOS调用相机拍照或从相册选择照片

作者: sfiveaa | 来源:发表于2017-06-09 17:27 被阅读0次

    1、在info.plist中添加Privacy - Photo Library Usage Description、Privacy - Camera Usage Description两个字段,这两个字段用于获取系统相机和相册权限。如果没有获取权限调用相机或相册程序回出现crash

    2、给viewController添加UIImagePickerControllerDelegate、 UINavigationControllerDelegate两个代理

    3、调用相机或相册

    func selectPhoto() {
        let imagePicker: UIImagePickerController = UIImagePickerController()
        imagePicker.modalPresentationStyle = .overFullScreen
        imagePicker.delegate = self
        //照片是否可以编辑
        imagePicker.allowsEditing = true
        //imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary 从相册选择照片
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera //拍照
        //前置照相头是否可用,可用即使用前置摄像头,否则使用后置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice.front) {
            imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.front;
        } else {
            imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.rear;
        }
        //跳转到拍照界面或相册
        self.present(imagePicker, animated: true, completion: nil)
    }
    

    4、添加回调函数

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
    {
        var image : UIImage!
        if picker.allowsEditing {
            image = info[UIImagePickerControllerEditedImage] as! UIImage
        } else {
            image = info[UIImagePickerControllerOriginalImage] as! UIImage
        }
        self.dismiss(animated: true) {
            //拍照完成或选择照片完成之后返回 
            //处理获取到的照片等
        }
    }
    

    相关文章

      网友评论

          本文标题:iOS调用相机拍照或从相册选择照片

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