Search code examples
swiftuiimageviewdispatch-async

UIImageView is NIL


I have a default image in viewItem to make sure that it is working, it shows on the detail view of the splitview.

@IBOutlet weak var ImageView: UIImageView!

var imageCache = [String: UIImage]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.configureView()
}

func configureView() {
    if let detail: AnyObject = self.detailItem {
        if let label = self.detailDescriptionLabel {
            let dict = detail as [String: String]
            label.text = ""
            let s = dict["result"]
            let vr = NString(string: s!)
            let vrd = vr.doubleValue
            let value = ceil(vrd*20)
            let valueString = String(format: "%.0f", value)

            vresult.text = "\(valueString)%"

            getPic(dict)  // <---- trouble maker

            fitem.hidden = false
            ritem.hidden = false
        }
    } else {
        navigationController?.popViewControllerAnimated(true)
    }
}

func getPic(item: [String: String]) {
    var chachedImage = self.imageCache[item["image"]!]

    println(item["image"]) // <-- prints out the url

    if cachedImage == nil {
        var imgUrl = NSURL(string: item["image"]!)
        let request: NSURLRequest = NSURLRequest(URL: imgUrl!)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {( reponse: NSURLResponse!, data: NSData!, error; NSError!) -> Void in
            if error == nil {
                cachedImage = UIImage(data: data)

                println("got here no problem") // <-- prints out

                self.imageCache[item["image"]!] = cachedImage

                println(self.imageCache) // <-- prints reference OK

                dispatch_async(dispatch_get_main_queue(), {
                    self.ImageView.image = cachedImage  // <---- offender
                })
            } else {
               println("Error: \(error.localizedDescription)")
            }
        })
    } else {
        dispatch_async(dispatch_get_main_queue(), {
            self.ImageView.image = cachedImage
        })
    }
}

ImageView is coming up nil every time.

fatal error: unexpectedly found nil while unwrapping an Optional value

but the default image shows. I've moved this out of the dispatch and even tried setting it straight from the viewDidLoad() always errors. It used to be a UIWebView and worked perfectly except that it would not cache anything. Since loading these images is a lot of work, I thought caching would be good, I've got caching working for thumbnails in the MASTER view.


Solution

  • Well silly me. I've been working on this for a few days, I got the great idea to try and change the name, and it worked. I tried changing it back and it broke, apparently you can't use ImageView as a variable!