The problem am facing is placing the picture i choose from the gallery into theUIImageView
(imageChosen).
The code runs fine without any errors but the picture i chose is not set to the "imageChosen"
here is my code
class postChoices: UIViewController {
@IBOutlet weak var imageChosen: UIImageView!
@IBAction func gallery(sender: AnyObject) {
var image = UIImagePickerController()
//image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
image.allowsEditing = false
self.presentViewController(image, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image2: UIImageView!, editingInfo: NSDictionary!) {
// let selectedImage : UIImageView = image
imageChosen.image = image2.image
}
}
//Complete solution with delegates and image handling
import UIKit
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
@IBOutlet weak var myImageView: UIImageView!
let picker = UIImagePickerController()
@IBAction func gallery(sender: AnyObject) {
if UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary) != nil {
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
presentViewController(picker, animated: true, completion: nil)
} else {
noCamera()
}
}
func noCamera(){
let alertVC = UIAlertController(title: "No Camera", message: "Sorry, Gallery is not accessible.", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style:.Default, handler: nil)
alertVC.addAction(okAction)
presentViewController(alertVC, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
picker.delegate = self //the required delegate to get a photo back to the app.
}
//MARK: - Delegates
//What to do when the picker returns with a photo
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2
myImageView.contentMode = .ScaleAspectFit //3
myImageView.image = chosenImage //4
dismissViewControllerAnimated(true, completion: nil) //5
}
//What to do if the image picker cancels.
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
}