Updated 30 November 2021
UIImagePickerController is a view controller that is used for choosing items from the user’s media library(like- images, videos)
It is managing the user interface when we choose the picture or video from the library.
Now, we are going to use UIImagePickerController in a project.
Let’s start,
First, we create an instance for ImagePickerController and add protocols for adopting a protocol to properly use UIImagePickerController
1 2 3 4 5 6 7 8 9 10 |
class ViewController: UIViewController, UIImagePickerControllerDelegate & UINavigationControllerDelegate { @IBOutlet weak var imageview: UIImageView! let imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self } } |
Now, we will create the action for the Add Image Button and here we call UIImagePickerController
1 2 3 4 5 6 |
@IBAction func AddimageAction(_ sender: UIButton) { imagePicker.allowsEditing = false imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } |
We need to set whether the image picker wants to allow editing or not and also need to set source type.
You can set the source type .photoLibarary or .savedPhotosAlbum.
The basic difference between photoLibrary and savedPhotosAlbum is .photoLibrary gives access to users of any photos available on the device, with albums, and camera roll.
The .savedPhotosAlbum save images locally on your device but has no access to albums or any of the other views.
Now, we need to implement the delegate method “imagePickerController:didFinishPickingMediaWithInfo:” .
1 2 3 4 5 6 7 8 |
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { imageview.contentMode = .scaleAspectFit imageview.image = pickedImage } dismiss(animated: true, completion: nil) } |
At last, we will dismiss the view controller that was presented before
1 2 3 |
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } |
The UIImagePickerController makes it easy for users to select images from their device and keeps the user experience consistent with the other apps that also use it.
Lastly, Please share your thoughts with us in the comment area.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.