To select a photo from your library we can use the built in UIImagePickerController.
This is simple to use and allows you to select and use an image already saved to your device.
To start with we create a new UIImagePickerController class with:
let imagePickerController = UIImagePickerController()
We then assign its delegate and set its sourceType which below we set to PhotoLibrary so we can access our photos.
Finally we present the newly created controller using presentViewController.
1 2 3 4 5 6 7 8 9 |
@IBAction func selectPhotoButtonPressed(sender: UIButton) { let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.allowsEditing = false imagePickerController.sourceType = .PhotoLibrary self.presentViewController(imagePickerController, animated: true, completion: nil) } |
The code above is wrapped in a button press action but is does not need to be.
To use the imagePickerController we need to implement the delegate UINavigationControllerDelegate and the UIImagePickerControllerDelegate.
We are going to need to implement a couple of delegate methods from the UIImagePickerControllerDelegate.
The first is imagePickerController:didFinishPickingMediaWithInfo
1 2 3 4 5 6 7 8 9 10 11 |
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { guard let imageSelected = info[UIImagePickerControllerOriginalImage] as? UIImage else { return } photoImageView.image = imageSelected picker.dismissViewControllerAnimated(true, completion: nil) } |
This method is used to select the image and close the controller. Here we use the image of imageSelected and assign it to the UIImageView photoImageView to display it.
We then close the UIImagePickerViewController with dismissViewController.
The second is imagePickerControllerDidCancel. This handles cancelling the imagePickerController.
1 2 3 |
func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.dismissViewControllerAnimated(true, completion: nil) } |
You can view an example project of this code here