dipper dipper - 9 months ago 23
Swift Question

Image isn't being sent to next view controller

I'm trying to send an image from one view to another via a segue and display said image in an

UIImageView
.

The following code gets the picture and assigns it to a global
UIImage
variable. Excuse the graphics code, I've been playing around trying to merge an image and a text field to create a single image:

@IBAction func sendSnap(_ sender: Any) {
var size = CGSize(width: self.takenImage.size.width, height: self.takenImage.size.height)
UIGraphicsBeginImageContext(size)
let areaSize = CGRect(x: 0, y: 0, width: self.takenImage.size.width, height: self.takenImage.size.height)
self.takenImage.draw(in: areaSize)
var outputImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.finalImage = outputImage
}


I then created a segue with an identifier going from a button to the destination controller and handled the data within the prepare func:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showFinal" {
let lastVC = segue.destination as! TestingViewController
lastVC.image = self.finalImage
}
}


The problem I'm having is for some reason, the
lastVC.image
isn't being assigned with
self.finalImage
.

I've checked the height/width of final image to ensure it's not empty.

Here is my code for
TestingViewController
(destination):
@IBOutlet weak var displayImage: UIImageView!
var image: UIImage = UIImage()

override func viewDidLoad() {
super.viewDidLoad()
self.displayImage.image = image
print(image.size.height)
// Do any additional setup after loading the view.
}


image.size.height
is printing 0.0 in the console so I definitely know the image isn't being sent across... but I'm unsure where to go from here?

Any help would be appreciated, thanks.

Answer Source

I'm guessing you have both

@IBAction func sendSnap(_ sender: Any) {}

and a segue assigned to the same button. When you tap the button, the segue is triggered along with prepare() and sendSnap() is called. Which one is running first?

A better approach would be to create a "named" segue, then have the button tap call sendSnap(), and at the end of sendSnap() call:

performSegue(withIdentifier: "showFinal", sender: self)