Search code examples
swiftuiimageviewviewcontroller

Passing UIImage array between two ViewControlllers losing values


I'm passing an array of images between 2 VCs in memory. I don't know if this is a problem and impossible to do? I'm getting blank images in the second view controller when it references the first's array of UIImages.

class ViewPDFAfterSnapshotViewController: UIViewController {
    @IBOutlet weak var pdfView: PDFView!
    @IBOutlet weak var confirmUploadButton: UIButton!
    
    @IBOutlet weak var CancelUploadButton: UIButton!
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let vc = CameraViewController()
        // convert to PDF
        let pdfDocument = PDFDocument()
        for i in 0 ..< vc.images.count {
            let image = vc.images[i]
              let pdfPage = PDFPage(image: image)
              pdfDocument.insert(pdfPage!, at: i)
        }
        
        pdfView.displayMode = .singlePageContinuous
        pdfView.autoScales = true
        pdfView.displayDirection = .vertical
        pdfView.document = pdfDocument
        
    }
    

Edit 1: Ok from the feedback I got and the article linked I did this:

func transistionToPDFView(){
        
        let vc = ViewPDFAfterSnapshotViewController()
        vc.images = images
        
        
        navigationController?.pushViewController(vc, animated: true)
        

        
        view.window?.rootViewController = vc
        view.window?.makeKeyAndVisible()
    }

Solution

  • You are creating new instance of CameraViewController. That's incorrect. Every time you create new instance of CameraViewController it will be altogether new reference.

    You should access the already available / created instance of the CameraViewController.

    When performing segue or navigating between view controllers, you can pass the data from one view controller to another.

    Let's say you have A and B view controllers, at the time navigation between A to B you can do something like this:

    let b = B() // Instantiate B view controller from storyboard with identifier

    b.images = images // Data to pass to the next view controller

    If you want to understand it properly, you can refer to this article:

    https://www.hackingwithswift.com/example-code/system/how-to-pass-data-between-two-view-controllers