Tuesday, November 18, 2014

UIImagePickerControllerSourceType.Camera - Take a photo

1. Drag a UIImageView and Button to the storyboard.
Adjust the view mode of UIImageView to Aspect Fit

2. Control-drag to create:

    @IBOutlet weak var picture: UIImageView!
    
    @IBAction func takePhoto(sender: AnyObject) {

    }

3. Add delegates

class ViewController: UIViewControllerUIImagePickerControllerDelegateUINavigationControllerDelegate {



4. Complete Code:

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var picture: UIImageView!
    
    @IBAction func takePhoto(sender: AnyObject) {
        if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
            var pickerController = UIImagePickerController()
            pickerController.delegate = self
            pickerController.sourceType = UIImagePickerControllerSourceType.Camera
            self.presentViewController(pickerController, animated: true, completion: nil)
        }
    }
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        let pictureTaken = info[UIImagePickerControllerOriginalImage] as UIImage
        self.picture.image = pictureTaken
        UIImageWriteToSavedPhotosAlbum(pictureTaken, nil, nil, nil)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

No comments:

Post a Comment