I faced same problem in my application. My solution was:
var imagePicker: UIImagePickerController?
func openCamera() -> Void {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .camera;
picker.allowsEditing = false
imagePicker = picker //made this way to avoid forced unwrapping in imagePicker
self.present(picker, animated: true, completion: nil)
}
}
func openLibrary() -> Void {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary;
picker.allowsEditing = true
imagePicker = picker
self.present(picker, animated: true, completion: nil)
}
}
and then I had to implement this:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
imagePicker?.dismiss(animated: true, completion: nil)
uploadImage(resizeImage) //my function to upload the selected image
imagePicker = nil
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
imagePicker?.dismiss(animated: true, completion: nil)
imagePicker = nil
}
Solution applied to Swift 4.2