- Open your View controller file.
- Handle Event - e.g.
buttonTapped
in following example. - Add code snippet as follows
class YourViewController: UIViewController {
func buttonTapped(_ sender: AnyObject?) {
// 1. Create image picker controller
let imagePicker = UIImagePickerController()
// 2. Assign delegate
imagePicker.delegate = self
// 3. Set camera or other
imagePicker.sourceType = .camera // .photoLibrary // .savedPhotosAlbum
// 4. allow Editing only if required
imagePicker.allowsEditing = true
// present image picker.
present(imagePicker, animated: true, completion: nil)
}
}
- Add delegate methods as follows.
extension YourViewController: UIImagePickerControllerDelegate {
func imagePickerController(
controller: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
) {
controller.dismiss(animated: true, completion: nil)
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
// Do something when image is selected
}
}
func imagePickerControllerDidCancel(controller: UIImagePickerController) {
imagePicker.dismiss(animated: true, completion: nil)
}
}