设置用户权限请求:
在Info.plist文件中添加Privacy - Camera Usage Description和Privacy - Photo Library Usage Description字段
设置代理:
class BasicPhotoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
代码实现:
- 让用户选择从相册上传照片或是拍照
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "打开相机", style: .default, handler: { (alertCamera) in let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .camera picker.allowsEditing = true if UIImagePickerController.isSourceTypeAvailable(.camera) { self.present(picker, animated: true, completion: nil) } else { self.showAwardInfo(info: "请打开相机权限") } })) alert.addAction(UIAlertAction(title: "打开相册", style: .default, handler: { (alertAlbum) in let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .photoLibrary picker.allowsEditing = true if UIImagePickerController.isSourceTypeAvailable(.camera) { self.present(picker, animated: true, completion: nil) } else { self.showAwardInfo(info: "请打开相册权限") } })) alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil)
- 实现代理方法
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let choseImage = info[UIImagePickerControllerOriginalImage] as? UIImage { picker.dismiss(animated: true) { //自定义对图片choseImage处理 } } }