如何将选定的图像从 UIImagePicker 传递到 UIViewController

How to pass selected image from UIImagePicker to the UIViewController

我已经在我的应用程序中实现了 UIImagePicker,但我正在努力将 UIImage 传递给启动选择器的 UIViewController(请参阅代码中的注释下)

下面的代码是存储在Extensions/ImageUploader.swift

中的扩展
import UIKit
import Firebase

extension UIViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{


    public func ImagePicker() {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.allowsEditing = true
        // mediaType is image only by default

        present(picker, animated: true, completion: nil)

    }


    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        var selectedImageFromPicker: UIImage?

        if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
            selectedImageFromPicker = editedImage
        }
        if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            selectedImageFromPicker = originalImage
        }

        picker.dismiss(animated: true, completion:{print("Image upload started")})// Closing the window before the upload, so upload can continue in background while user finishes the form

           // Here I want to pass the selectedImageFromPicker to the ViewController that initiated the imagePicker - how do I do that??


        })
        }
}

createActivityVC 中,我有这个 IBAction 来访问 photo library 并启动选择器 - self.imagePicker()

@IBAction func addPictureBtnWasPressed(_ sender: Any) {

    PHPhotoLibrary.requestAuthorization({(status:PHAuthorizationStatus) in
        switch(status) {

       case .notDetermined:

        // Access has not been determined.
        PHPhotoLibrary.requestAuthorization({ (newStatus) in

            if (newStatus == PHAuthorizationStatus.authorized) {
                // Access has been granted.

                self.imagePicker() 
            }

            else {

            }
        })
        break

    case .restricted:
        break

    case .denied:
        // Access has been denied.
        print("Acccess to photo denied")
        break

    case .authorized:
        // Access has been granted.
        print("Access to photo authorized")

         self.imagePicker()

         break


      }
   })
}

我想将 selectedImageFromPicker 传递给 viewController createActivityVC。如何才能做到这一点?我宁愿不具体命名 viewController,而是让它是动态的,这样 imagePicker 就可以在可能的情况下跨多个 ViewControllers 使用。

在您的表单中,您是否实现了 UIImageView?如果是这样,在您的

public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

你可以说:

myFormImageView.image = selectedImageFromPicker

然后当您提交表单时,您可以上传表单信息 + 图片数据

更新:

我通过子类化 UIIMagePickerController 的方法

import UIKit

protocol ImagePickerDelegate {
    func imagePicked(image: UIImage)
}

class myPickerViewController: UIImagePickerController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{

    var imagePickerDelegate:ImagePickerDelegate!

    override func viewDidLoad() {
        super.viewDidLoad()
        allowsEditing = true
        delegate = self
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
            imagePickerDelegate.imagePicked(image: selectedImage)
        dismiss(animated: true, completion: nil)
    }

}

class ViewController : UIViewController, ImagePickerDelegate {

    func imagePicked(image: UIImage) {
        imagePicked = image
    }


    var imagePicked:UIImage! {
        didSet {
            imageView.image = imagePicked
        }
    }

    let button: UIButton = {
       let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle("Select an image", for: .normal)
        button.backgroundColor = .red
        button.addTarget(self, action: #selector(handleImagePicker), for: .touchUpInside)
        return button
    }()

    let imageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.contentMode = .scaleAspectFill
        iv.layer.masksToBounds = true
        iv.layer.borderWidth = 2
        iv.layer.borderColor = UIColor.black.cgColor
        return iv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Get image via Delegate"
        view.backgroundColor = .white

        view.addSubview(button)
        view.addSubview(imageView)

        button.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive = true
        button.heightAnchor.constraint(equalToConstant: 30).isActive = true
        button.widthAnchor.constraint(equalToConstant: 150).isActive = true
        button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

        imageView.topAnchor.constraint(equalTo: self.button.topAnchor, constant: 50).isActive = true
        imageView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
        imageView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
        imageView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -50).isActive = true

    }

    @objc func handleImagePicker() {
        let myPickerVC = myPickerViewController()
        myPickerVC.imagePickerDelegate = self

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

}

你创建一个新项目并粘贴它会工作的整个代码,我想,就像我一样。 希望对你有帮助

中Swift4.2

在 Swift 4.2 中,从 imagePicker 获取图像的代码发生了如下变化。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
        imagePickerDelegate.imagePicked(image: selectedImage)
        dismiss(animated: true, completion: nil) 
}