第一步:需要在项目中的Info.plist中添加相应的键
访问相册:Privacy - Photo Library Usage Description
访问摄像头:Privacy - Camera Usage Description
它们对应的值可以随意填写,但是其值是显示给用户的信息
第二步:请求访问
***注意:如果用button设置接收图片,则此button的类型不能为系统样式,即 addImageBtn.buttonType = .system 是无法设置成功的。 求大手告诉原因~~
这个例子中一整个图片添加是一个Button点击触发选择图片事件
首先要遵守UIImagePickerControllerDelegate,和UINavigationControllerDelegate
然后在button点击触发的事件中添加如下代码
@IBAction func chosePhoto(_ sender: UIButton) {
guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary)else{ //如果是要访问相机只需要将.photoLibrary改为.camera即可
print("无法获得相册授权")
return
}
let picker = UIImagePickerController()
picker.allowsEditing = false //不允许编辑图片
picker.sourceType = .photoLibrary //选择器访问的是相册(如果是访问相机则将.photoLibrary改为.camera)
picker.delegate = self //设置代理
self.present(picker, animated: true, completion: nil)//以模态视图弹出选择器
}
guard 的作用是保证应用获得用户授权之后才能访问相册
第三步:访问完相册之后就要让在相册中被点击的图片设置为Button的图片
//必须要先设置picker的代理
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//被点击的图片的信息保存在info字典中
self.albumBtn.setImage(info[UIImagePickerControllerOriginalImage] as? UIImage, for: .normal)
self.albumBtn.imageView?.contentMode = .scaleAspectFill
self.albumBtn.imageView?.clipsToBounds = true
dismiss(animated: true, completion: nil)
}
5.15更新****************************************
之前的版本里在打开相册的时候只能选择图片而不能选择视频,这是因为UIImagePickerViewController.mediaTypes为设置,当mediaTypes没设置的时候默认为kUTTypeImage ,即:只选择图片
所以当要选择视频的时候只需要将mediaTypes 设置为 kUTTypeMovie即可
例:
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = .photoLibrary
picker.mediaTypes = [kUTTypeMovie as String , kUTTypeImage as String] //可以选择视频 和 图片
present(picker, animated: true, completion: nil)
然后在 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])方法中判断选择的是图片还是视频之后在做需要做的操作
例:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let type = info[UIImagePickerControllerMediaType] as? String //获取所选中项目的类型
if type == kUTTypeMovie as String{ //判断选中的是图片还是视频
let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
self.dismiss(animated: true, completion: nil)
//写出你要做的操作,我这里的示例是做的共享的操作
let activityViewController = UIActivityViewController(activityItems: [videoURL], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}else{
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.selectedImage = image
self.dismiss(animated: true, completion: nil)
let shareVC = UIActivityViewController(activityItems: [image], applicationActivities: nil)
shareVC.popoverPresentationController?.sourceView = self.view
present(shareVC, animated: true, completion: nil)
}
}