Skip to content

Instantly share code, notes, and snippets.

@soggybag
Created November 8, 2015 18:04
Show Gist options
  • Save soggybag/377ce59ac5e7e04b6e83 to your computer and use it in GitHub Desktop.
Save soggybag/377ce59ac5e7e04b6e83 to your computer and use it in GitHub Desktop.
Minimal ViewController using Image Picker to take a picture with the camera and display it in an image view.
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// Must be declared here!
var picker = UIImagePickerController()
// IBOutlets
@IBOutlet weak var backgroundImageView: UIImageView!
// IBActions
@IBAction func takePhotoTapped(sender: UIButton) {
if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil {
// ! Creating the image picker here doesn't work!
// picker = UIImagePickerController()
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.Camera
picker.cameraCaptureMode = .Photo
picker.showsCameraControls = true
picker.modalPresentationStyle = .FullScreen
presentViewController(picker, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "Camera Error", message: "No Camera", preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(ok)
presentViewController(alert, animated: true, completion: nil)
}
}
// Image Controller Delegate methods
// Image was chosen
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
print("Saving image to photos")
UIImageWriteToSavedPhotosAlbum(chosenImage, self, nil, nil)
print("setting image view")
print(chosenImage)
self.backgroundImageView.image = chosenImage
} else {
print("chosen image has problem...")
}
dismissViewControllerAnimated(true, completion: nil)
}
// Image picker canceled
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment