UIImagepicker controller allowsEditing not working

by

Using native image picker system is easy and solves everyday basic needs of most apps.

UIImagePickerController
A view controller that manages the system interfaces for taking pictures, recording movies, and choosing items from the user’s media library.

Here is an example code that lets user pick images from photo library:


pickerController = UIImagePickerController()
pickerController?.delegate = self
pickerController?.mediaTypes = [“public.image”]
pickerController?.sourceType = .photoLibrary
self.present(pickerController!, animated: true, completion: nil)

We need to implement delegate methods that provides us media info from which we can extract image in our case if available. Here is a code


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.originalImage] as? UIImage{
    }
}

info
A dictionary containing the original image and the edited image, if an image was picked; or a filesystem URL for the movie, if a movie was picked. The dictionary also contains any relevant editing information. The keys for this dictionary are listed in Editing Information Keys.

Our picked image resides inside the key .originalImage which is optional so if something went wrong then it will be nil.

Now, UIImagePickerController also supports basic crop. To activate crop we set the allowsEditing property to true. By default it is false.

allowsEditing
A Boolean value indicating whether the user is allowed to edit a selected still image or movie.

Here is the code with crop enabled:


pickerController = UIImagePickerController()
pickerController?.delegate = self
pickerController?.allowsEditing = true
pickerController?.mediaTypes = [“public.image”]
pickerController?.sourceType = .photoLibrary
self.present(pickerController!, animated: true, completion: nil)
But hang on, very commonly we will find that even when we enabled crop in UIImagePickerController and cropped our image in crop screen we did not receive the cropped pic in our delegate. This is because of a simple mistake. We are still extracting our image from .originalImage. As name suggests it provides only original image if available. We need cropped image. Our cropped image resides in .editedImage. Here is the code

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.editedImage] as? UIImage{
    }
}

Conclusion: When we edit the image in picker controller, edited image will be received in .editedImage

You might also like: How to get Deprecated keyWindow in Swift

More Articles

Recommended posts