制作照片
并从库中选择无效
我使用的是Swift 4,我的代码如下:
class ProfileViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
@objc func changeThePicture(sender: UITapGestureRecognizer) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
alertController.addAction(UIAlertAction(title: "Choose a photo from your gallery", style: UIAlertAction.Style.default, handler: { (action) -> Void in
self.changePicture()
}))
alertController.addAction(UIAlertAction(title: "Make a photo", style: UIAlertAction.Style.default, handler: { (action) -> Void in
self.openCamera()
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
func changePicture() {
self.checkPhotoLibraryPermission {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary) {
self.imagePicker.allowsEditing = false
self.imagePicker.sourceType = .photoLibrary
self.imagePicker.mediaTypes = [kUTTypeImage as String]
self.present(self.imagePicker, animated: true, completion: nil)
}
}
}
func openCamera() {
self.checkMakePhotoPermission {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
self.imagePicker.allowsEditing = false
self.imagePicker.sourceType = .camera
self.imagePicker.mediaTypes = [kUTTypeImage as String]
self.present(self.imagePicker, animated: true, completion: nil)
}
}
}
@IBAction func changePictureButton(_ sender: UITapGestureRecognizer) {
self.changeThePicture(sender: sender)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("media")
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.chosenImage = pickedImage
userProfilePic.imageView.image = pickedImage
uploadImage(userImage: chosenImage) { (result) in
}
}
dismiss(animated:true, completion: nil)
}
仅当我拍照时才打印媒体...但是当我从图库中选择时什么也没发生,我会收到此错误
发现扩展名时遇到[发现]错误:错误 域= PlugInKit代码= 13“查询已取消” UserInfo = {NSLocalizedDescription =查询已取消}
答案 0 :(得分:0)
您的问题是因为您在完全关闭图像选择器模式之前执行逻辑(上传图像)。
将您的方法更改为此:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("media")
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
dismiss(animated:true) { [weak self] in
self?.chosenImage = pickedImage
self?.userProfilePic.imageView.image = pickedImage
self?.uploadImage(userImage: chosenImage) { (result) in
}
}
} else {
dismiss(animated:true, completion: nil)
}
}