caipivara
7/8/2015 - 11:45 PM

iOS - Swift - Show image picker for gallery/camera, Thanks to http://www.theappguruz.com/blog/user-interaction-camera-using-uiimagepickercon

iOS - Swift - Show image picker for gallery/camera, Thanks to http://www.theappguruz.com/blog/user-interaction-camera-using-uiimagepickercontroller-swift/

public class WPLoginViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var imageHolderButton: UIButton!

    // MARK: - IBActions
    
    @IBAction func getImage(sender: AnyObject) {
        let alert:UIAlertController = UIAlertController(title: "Choose Image",
            message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        
        let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default) { UIAlertAction in
            self.openCamera()
        }
        let gallaryAction = UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default) { UIAlertAction in
            self.openGallary()
        }
        
        alert.addAction(cameraAction)
        alert.addAction(gallaryAction)
        
        self.presentViewController(alert, animated: true, completion: nil)
    }
    
    // MARK: Image Pick Management
    
    func openCamera() {
        let picker = UIImagePickerController()
        
        if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
            picker.sourceType = UIImagePickerControllerSourceType.Camera
            picker.delegate = self
            presentViewController(picker, animated: true, completion: nil)
        }
        else {
            openGallary()
        }
    }
    
    func openGallery() {
        let picker = UIImagePickerController()
        picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    }
}

extension WPLoginViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    public func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        picker.dismissViewControllerAnimated(true, completion: nil)
        imageHolderButton.setImage(image, forState: .Normal)
    }
    
}