TheTurtle TheTurtle - 18 days ago 10
Swift Question

Impossible to pass UIImage between 2 view controllers (without storyboard)

In the first ViewController (AViewController), I set the camera. When the picture is captured, I present an other ViewController (BViewController) which contains a UIImageView. The problem is the UIImageView in BViewController doesn’t show the picture captured in AViewController. I specify that I don’t use storyboard.

Does anyone have an idea to fix this fail ? Did I miss something ? Thanks for you help!

class AViewController: UIViewController {

...

func capture(){

if let videoConnection = stillImageOutput!.connection(withMediaType: AVMediaTypeVideo) {
videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(sampleBuffer, error) in
if (sampleBuffer != nil) {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let dataProvider = CGDataProvider(data: imageData as! CFData)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)

let imageSaved = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right)

self.present(BViewController(), animated: false, completion: { Void in
BViewController().integrate(image: imageSaved)
})
}
}
}
}


================================================================

class BViewController : UIViewController {

let imageView = UIImageView()

override func viewDidLoad() {
super.viewDidLoad()

imageView.frame = view.bounds
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
view.addSubview(imageView)

}

func integrate(image: UIImage){
imageView.image = image
}
}

Answer
self.present(BViewController(), animated: false, completion: { Void in   
    BViewController().integrate(image: imageSaved)
})  

The phrase BViewController() means "make a completely new view controller". But you say it twice! So the view controller you present (first line) and the view controller you give the image to (second line) are two completely different view controllers.