简体   繁体   中英

Swift iOS8 asynchronous image

I need to cache the image in Swift on iOS 8. I have a custom Table Cell View.

Here's my code:

import UIKit

class WorksTableViewCell: UITableViewCell {

  @IBOutlet var workImage: UIImageView!
  @IBOutlet var workTitle: UILabel!
  @IBOutlet var workDescription: UILabel!

 func configureCellWith(work: Work){
    workTitle.text = work.title 
    workDescription.text = work.description

    if let url = NSURL(string: work.image) {
      if let data = NSData(contentsOfURL: url) {
        var thumb = UIImage(data: data)
        workImage.image = thumb
      }
    }
  }
}

Create a dictionary mapping a String to a UIImage in the table's view controller and modify the data in the cellForRowAtIndexPath function. Jameson Quave has a nice tutorial on this very issue found here . It's updated to use new Swift 1.2 syntax as well.

Thanks I fixed like this:

import UIKit

class WorksTableViewCell: UITableViewCell {


  @IBOutlet var workImage: UIImageView!
  @IBOutlet var workTitle: UILabel!
  @IBOutlet var workDescription: UILabel!

  var imageCache = [String:UIImage]()

  func configureCellWith(work: Work){

    workTitle.text = work.title
    workDescription.text = work.description

    var imgURL = NSURL(string: work.image)

    // If this image is already cached, don't re-download
    if let img = imageCache[work.image] {
      workImage.image = img
    }else {
      // The image isn't cached, download the img data
      // We should perform this in a background thread
      let request: NSURLRequest = NSURLRequest(URL: imgURL!)
      let mainQueue = NSOperationQueue.mainQueue()

      NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
        if error == nil {
          // Convert the downloaded data in to a UIImage object
          let image = UIImage(data: data)
          // Store the image in to our cache
          self.imageCache[work.image] = image
          // Update the cell
          dispatch_async(dispatch_get_main_queue(), {
            self.workImage.image = image
          })
        }else {
          println("Error: \(error.localizedDescription)")
        }
      })

    }
  }
}

You can also create a UIImage extension and just call the async function in the configureCellWith function if you want a cleaner solution for Swift 3.

    import Foundation
    import UIKit

    let imageCache = NSCache <AnyObject,AnyObject>()

    extension UIImageView {

        func loadUsingCache(_ theUrl: String) {

        self.image = nil

            //check cache for image
            if let cachedImage = imageCache.object(forKey: theUrl as AnyObject) as? UIImage{
        self.image = cachedImage
        return
    }

    //otherwise download it
    let url = URL(string: theUrl)
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in

        //print error
        if (error != nil){
            print(error!)
            return
        }

        DispatchQueue.main.async(execute: {
            if let downloadedImage = UIImage(data: data!){
                imageCache.setObject(downloadedImage, forKey: theUrl as AnyObject)
                self.image = downloadedImage
            }
        })

    }).resume()
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM