dipper dipper - 1 year ago 50
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


The following code gets the picture and assigns it to a global
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)
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()!
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
isn't being assigned with

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

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

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

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download