Implementing UIImagePickerController in Swift

964 views Asked by At

The application runs just fine and allows me to select a photo. However, when I go to select a different photo the pickAnImage button won't work. What is the best way to allow the user to select a different image to view? Any help is appreciated.

import UIKit

    class ViewController: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate {


        @IBOutlet weak var imageView: UIImageView!

        let imagePicker = UIImagePickerController()

        @IBAction func pickAnImage(sender: AnyObject) {


            imagePicker.allowsEditing = false
            imagePicker.sourceType = .PhotoLibrary
            self.presentViewController(imagePicker, animated: true, completion: nil)


        }


        func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info:  [NSObject : AnyObject]) {
            if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {

                imageView.contentMode = .ScaleAspectFit
                self.imageView.image = pickedImage


            }

              dismissViewControllerAnimated(true, completion: nil)

        }


        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.

            imagePicker.delegate = self
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }


    }
1

There are 1 answers

2
Jay Bhalani On

try this code :

import MobileCoreServices

class SecondViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate {

   @IBOutlet var img:UIImageView!=nil

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

   override func didReceiveMemoryWarning() 
   {
       super.didReceiveMemoryWarning()

   }

   @IBAction func buttonTapped(AnyObject)
   {
     if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            println("Button capture")
            var imag = UIImagePickerController()
            imag.delegate = self
            imag.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            //imag.mediaTypes = [kUTTypeImage];
            imag.allowsEditing = false
            self.presentViewController(imag, animated: true, completion: nil)
        }
   }

   func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
        let selectedImage : UIImage = image
       //var tempImage:UIImage = editingInfo[UIImagePickerControllerOriginalImage] as UIImage
        img.image=selectedImage
        self.dismissViewControllerAnimated(true, completion: nil)    
   }
 }