Taking and sharing photos is an important feature of many apps. Using the UIImagePickerViewController is a simple and easy way of enabling your user to either take a new photo or get an existing one from the user’s photo library.
Tutorial:
First of all, we want to start a new single application template project. We want to set up our main view controller, with the main image view, camera and library button.
Then we want to add an important string to our info.plist. We need to add an NSCameraUsageDescription so that we can access the devices’ camera. This is a small sentence that describes to the user why your app requires access to the camera. My sentence is only an example, you can replace it with any description you’d like.
Then we have to implement the code within our UIViewController to handle the button presses, present the UIImagePickerViewController and then handle the UIImagePickerViewControllerDelegate.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
// MARK: ImagePickerViewController | |
class ImagePickerViewController: UIViewController { | |
// MARK: Outlets | |
@IBOutlet var cameraButton: UIButton! | |
@IBOutlet var libraryButton: UIButton! | |
@IBOutlet var mainImageView: UIImageView! | |
// MARK: IBAction Methods | |
@IBAction func camera(sender: Any?) { | |
presentUIImagePicker(sourceType: .camera) | |
} | |
@IBAction func library(sender: Any?) { | |
presentUIImagePicker(sourceType: .photoLibrary) | |
} | |
// MARK: Helper Methods | |
private func presentUIImagePicker(sourceType: UIImagePickerControllerSourceType) { | |
let picker = UIImagePickerController() | |
picker.delegate = self | |
picker.sourceType = sourceType | |
present(picker, animated: true, completion: nil) | |
} | |
} | |
// MARK: UIImagePickerControllerDelegate and UINavigationControllerDelegate | |
extension ImagePickerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { | |
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) { | |
guard let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage else { | |
dismiss(animated: true, completion: nil) | |
return | |
} | |
mainImageView.image = chosenImage | |
dismiss(animated: true, completion: nil) | |
} | |
@objc func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { | |
dismiss(animated: true, completion: nil) | |
} | |
} |
Here is the full source code for the project: