SamYoungNY
SamYoungNY

Reputation: 6624

Unable to segue fetched Image

Given the first part of this function which DL's a String from JSON doc, converts to NSURL, and then converts into UIImage to prepare it prior to next screen. I want to transfer this UIImage into next screen where I prepared IBOutlet 'imageView' for in ViewController2.

I am calling this function in ViewDidLoad() in ViewController1.

BUT I can't figure out how to push the image to the next screen.

I prepared a Push segue in the storyboard attached to a custom button, and created an IBAction for it attached to ViewController1. I've tried prepareForSegue and other attempts involving instantiating the storyboard etc, even though the data appears to be getting fetched correctly and the segue works, no image shows up.

What am I doing wrong?? Thanks for any help!

func fetchAndPrepImages() {

    let url = NSURL(string:"https://something.json")
    let JSONData = NSData(contentsOfURL: url!)
    let json = JSON(data: JSONData!)
    var err: NSError?
    let count: Int? = json["entry"].arrayValue?.count

    if let ct = count {
        for index in 0...ct {
            if var thumbURL = json["entry"][index]["smimg"]["label"].stringValue {
                self.thumbURLS.append(thumbURL)
            }
        }
    }
    // prepare image for segue
    let nextImage = thumbURLS.formatItem()
    let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
    let imageURL: NSURL? = NSURL(string: nextImage)
    let request: NSURLRequest = NSURLRequest(URL: imageURL!)

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        if error == nil {
            println(data) // ** This prints (presumably) image data in the console ** 
            vc2.imageView?.image = UIImage(data: data) // no error, but no image coming up 

        }
    })
}

Upvotes: 0

Views: 72

Answers (2)

SamYoungNY
SamYoungNY

Reputation: 6624

I am not well versed with Xcode's built-in functions and prepareForSegue is one that I have used before but forgot about. User Christian Woerz suggested some solutions within the context of how I had framed my functions but I wasn't able to implement them accurately so I scrapped this approach and reframed it a bit. I moved the bottom (prep) half of the fetchAndPrep() function into the prepareForSegue() function and this worked. Sample code below:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "imagePush" {
        let nextImage = thumbURLS.formatItem()
        let vc2: ViewController2 = segue.destinationViewController as ViewController2

        let imageURL: NSURL? = NSURL(string: nextImage)
        let request: NSURLRequest = NSURLRequest(URL: imageURL!)

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            if error == nil {
                println(data)
                if let image = UIImage(data: data) {
                    vc2.imageView?.image = image
                } else {
                    println("there's an error")
                }

            }

        })
    } 
}

Upvotes: 0

Christian
Christian

Reputation: 22343

You should work with the prepareForSegue method and call your segue from within your sendAsynchronousRequestmethod. So first you should make a segue with an identifier like for example "imagePush". Then you set the image as your sender:

if error == nil {
    println(data) // ** This prints (presumably) image data in the console ** 
    self.performSegueWithIdentifier("imagePush", sender: UIImage(data: data)

}

In your prepareForSegue method you then just need to cast the sender as your UIImage. That should work, because the performSegue-method calls the prepareForSegue method before sending the segue.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "imagePush"{
        let vc2: ViewController2 = ViewController2()
        vc2.imageView?.image = sender as UIImage
    }
}

Upvotes: 1

Related Questions