Skip to content

Instantly share code, notes, and snippets.

@rtking1993
Last active February 4, 2018 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtking1993/a402e3b4e217a34bc44003f55f7c3f97 to your computer and use it in GitHub Desktop.
Save rtking1993/a402e3b4e217a34bc44003f55f7c3f97 to your computer and use it in GitHub Desktop.
Implementing the UIImagePickerViewController
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment