Accessing user photos using UIImagePickerView

in 7 simple steps

MORE TUTORIALS

Setup Storyboard

Go to Main.Storyboard, add a UIImageView and UIButton onto your ViewController as shown in the animation below,

Step 1 of 7

Connect UI Elements to your View Controller

Connect your UIImageView and UIButton to your ViewController as IBOutlets and Connect your UIButton to ViewController as an IBAction. As shown in the animation below,

Step 2 of 7

Inherit UIImagePickerControllerDelegate and UINavigationControllerDelegate Classes

Replace ViewController class with the following code below,

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

Step 3 of 7

Initialize UIImagePickerView

Initialize Image Picker view and connect to delegate as shown below

let imagePicker = UIImagePickerController()

override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view, typically from a nib.

  self.imagePicker.delegate = self
}

Step 4 of 7

Setup Upload Tapped

Modify upload tapped button

imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)

Step 5 of 7

Setup Delegate Methods

Paste the delegate methods below into your ViewController class.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
   if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
     self.imageView.contentMode = .scaleAspectFit
     self.imageView.image = pickedImage
   }
   dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
   dismiss(animated: true, completion: nil)
}

Step 6 of 7

Run and test

Hit the play button, you should be able to upload an image and see it appear on the image view.

Step 7 of 7