Tuesday, 11 November 2014

Swift + Pick Image From Photo Library Using UIImagePickerController

First Add and Import MobileCoreServices Framework.

Confirm to UIImagePickerControllerDelegate & UINavigationControllerDelegate protocol


import UIKit

import MobileCoreServices


class ViewController: UIViewControllerUIImagePickerControllerDelegateUIAlertViewDelegateUINavigationControllerDelegate
{

    var cameraUI: UIImagePickerController! = UIImagePickerController()
    
    
    override func viewDidLoad()
    {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        
    }

    //--- Take Photo from Photo Library ---//
    @IBAction func takePhotoFromPhotoLibrary(sender: AnyObject)
    {
          self.presentLibrary()
    }



    func presentLibrary()
    {
       
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
        {
            cameraUI = UIImagePickerController()
            cameraUI.delegate = self
            cameraUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            cameraUI.mediaTypes = [kUTTypeImage]
            cameraUI.allowsEditing = false
            
            self.presentViewController(cameraUI, animated: true, completion: nil)
        }
        else
        {
            // error msg

        }


    }
    
    //Mark- UIImagePickerController Delegate
    
    func imagePickerControllerDidCancel(picker:UIImagePickerController)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    



    func imagePickerController(picker:UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary)
    {
       if(picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary)
        {
            var selectedImage: UIImage = info[UIImagePickerControllerOriginalImage] as UIImage
            
            //show Image on Image View and do other stuf that you want
            
            self.dismissViewControllerAnimated(true, completion: nil)


        }
       
    }
 


 
}  

2 comments: