Установка изображения, взятого из галереи в UIImageView

проблема заключается в размещении изображения, которое я выбираю из галереи вUIImageView (imageChosen).

код работает нормально без каких-либо ошибок, но изображение, которое я выбрал, не установлено в "imageChosen"

вот мой код

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

    }


}

5 ответов


//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)
            }
        }

Демо-Проект


несколько проблем.

если вы посмотрите на документацию метода imagePickerController:didFinishPickingImage:editingInfo: был устаревшим в iOS 3.0.

это справедливая ставка, что это даже не называется. (У вас есть строка, которая настраивает контроллер представления в качестве комментария делегата, поэтому средство выбора изображений не будет вызывать методы делегата.

в своем imagePickerController:didFinishPickingImage:editingInfo: метод у вас есть image2, определенный как UIImageView. Это не так, это объектами UIImage.

вы должны раскомментировать строку image.delegate = self.

вы должны реализовать метод imagePickerController:didFinishPickingMediaWithInfo: вместо imagePickerController:didFinishPickingImage:editingInfo:.

вам, вероятно, также нужно добавить UIImagePickerControllerDelegate к определению вашего класса контроллера вида, чтобы компилятор знал, что ваш контроллер вида соответствует UIImagePickerControllerDelegate протокол.


    - (void) makeUIImagePickerControllerForCamera:(BOOL)camera {

         UIImagePickerController *picker = [[UIImagePickerController alloc] init];
         picker.delegate = self;
         picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;

         [picker setMediaTypes:[NSArray arrayWithObjects:(NSString *) kUTTypeImage, nil]];

         [self presentModalViewController: picker animated: YES];
    }

    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
        // Dismiss the picker
        [[picker parentViewController] dismissModalViewControllerAnimated:YES];

    // Get the image from the result
    UIImage* image = [info valueForKey:@"UIImagePickerControllerOriginalImage"];

    myUIImage.image = image;
}

этот код помог мне с Swift 3.0

internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        billImageView.contentMode = .scaleAspectFill
        billImageView.image = pickedImage
    }
    self.dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    self.dismiss(animated: true, completion: nil)
}

В Swift 3.0 в этом коде вы должны выбрать как опцию camera, так и Gallary

import UIKit
import Foundation
import AVFoundation
class HostVC: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate{    
@IBOutlet weak var imgHostProfile:UIImageView!
    let captureSession = AVCaptureSession()
    let stillImageOutput = AVCaptureStillImageOutput()
    var previewLayer : AVCaptureVideoPreviewLayer?
    var captureDevice : AVCaptureDevice?

 @IBAction func btnChangeprofileTapped(_ sender: UIButton)
    {


        DispatchQueue.main.async
            {
                let alert = UIAlertController(title: "Alert", message: "Choose profile picture from Camera or Gallery", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "Take a photo", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in
                    DispatchQueue.main.async
                        {
                            if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) ==  AVAuthorizationStatus.authorized {
                                self.Cemara()
                            } else {
                                AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in
                                    if granted == true {
                                        self.Cemara()
                                    } else {
                                        self.showalert(strMessage: Validation.kCameraAccess)
                                    }
                                })
                            }

                    }
                }))
                alert.addAction(UIAlertAction(title: "Choose from Library", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in
                    DispatchQueue.main.async
                        {
                            let imagepicker = UIImagePickerController()
                            imagepicker.delegate = self
                            imagepicker.sourceType = .photoLibrary

                            self.present(imagepicker, animated: true, completion: nil)
                    }
                }))

                alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in}))

                self.present(alert, animated: true, completion: nil)

        }


    }

    func Cemara()
    {
        DispatchQueue.main.async {
            if UIImagePickerController.availableCaptureModes(for: .rear) != nil
            {
                let imagePicker = UIImagePickerController()
                imagePicker.delegate = self
                imagePicker.sourceType = .camera
                self.present(imagePicker, animated: true, completion: nil)
            }
            else
            {
                self.noCamera()
            }
        }
    }

    //======================================================================
    //                  MARK: -  Camera  Code
    //======================================================================

    func noCamera()
    {
        captureSession.sessionPreset = AVCaptureSessionPresetHigh
        if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice]
        {
            for device in devices
            {
                if (device.hasMediaType(AVMediaTypeVideo))
                {
                    if(device.position == AVCaptureDevicePosition.front)
                    {
                        captureDevice = device
                        if captureDevice != nil
                        {
                            print("Capture device found")
                            beginSession()
                        }
                    }
                }
            }
        }
    }

    //======================================================================
    //                  MARK: - Camera Capture Start Session Code Here
    //======================================================================

    func beginSession()
    {
        do
        {
            try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
            if captureSession.canAddOutput(stillImageOutput)
            {
                captureSession.addOutput(stillImageOutput)
            }
        }
        catch
        {
            print("error: \(error.localizedDescription)")
        }
        guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else
        {
            print("no preview layer")
            return
        }
        self.view.layer.addSublayer(previewLayer)
        previewLayer.frame = self.view.layer.frame
        captureSession.startRunning()
        self.view.addSubview(imgHostProfile)


    }

    //======================================================================
    //                  MARK: - Gallary Code
    //======================================================================

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
    {
        if let imagedata = info[UIImagePickerControllerOriginalImage] as? UIImage
        {
            self.imgHostProfile.image = imagedata
            print(imagedata)


        }

        dismiss(animated: true, completion: nil)
    }