Swift3.0 调用系统相机、相册

2017-11-11  本文已影响0人  BrumeLoong

关于调用系统相机和相册需要在info.plist文件里面添加两个权限Privacy - Photo Library Usage Description 和 Privacy - Camera Usage Description ,都是String类型,内容任意的字符串即可;然后使用的时候需要遵守两个协议UIImagePickerControllerDelegate和UINavigationControllerDelegate。

func tapImage(){
        present(self.uploadAlertController, animated:true, completion: nil)
        self.initImagePickerController()
    }
    func initAlertController()
    {
        weak var blockSelf = self
        self.uploadAlertController = UIAlertController(title:nil, message: nil, preferredStyle:UIAlertControllerStyle.actionSheet)
        let takePhoto = UIAlertAction(title:"拍照", style:UIAlertActionStyle.default) { (action:UIAlertAction)in
            blockSelf?.actionAction(action: action)
        }
        let photoLib = UIAlertAction(title:"从相册选择", style:UIAlertActionStyle.default) { (action:UIAlertAction)in
            blockSelf?.actionAction(action: action)
        }
        let cancel = UIAlertAction(title:"取消", style:UIAlertActionStyle.cancel) { (action:UIAlertAction)in
            blockSelf?.actionAction(action: action)
        }
        self.uploadAlertController?.addAction(takePhoto)
        self.uploadAlertController?.addAction(photoLib)
        self.uploadAlertController?.addAction(cancel)
    }
    func initImagePickerController()
    {
        pick = UIImagePickerController()
        pick.delegate = self
        // 设置是否可以管理已经存在的图片或者视频
        pick.allowsEditing = true
    }
    func actionAction(action:UIAlertAction)
    {
        if action.title == "拍照" {
            self.getImageFromCamera(type: .camera)
        }else if action.title == "从相册选择" || action.title == "更换头像" {
            self.getImageFromPhotoLib(type: .photoLibrary)
        }
    }
    //拍照
    func getImageFromCamera(type:UIImagePickerControllerSourceType)
    {
        
        pick.sourceType = type
        self.present(pick, animated: true, completion:nil)
    }
    //相册选择
    func getImageFromPhotoLib(type:UIImagePickerControllerSourceType)
    {
        pick.sourceType = type
        self.present(pick, animated: true, completion:nil)
    }
    //MARK:- UIImagePickerControllerDelegate
    func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo info: [String :Any]){
        
        let type:String = (info[UIImagePickerControllerMediaType]as!String)
        //当选择的类型是图片
        if type == "public.image"
        {
            let img = info[UIImagePickerControllerOriginalImage]as?UIImage
            self.headImage.image = img
        }
    }
    
    func imagePickerControllerDidCancel(_ picker:UIImagePickerController){
        picker.dismiss(animated:true, completion:nil)
    }
上一篇下一篇

猜你喜欢

热点阅读