簡體   English   中英

Swift iOS8異步鏡像

[英]Swift iOS8 asynchronous image

我需要在iOS 8的Swift中緩存圖像。我有一個自定義的表格單元格視圖。

這是我的代碼:

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
      }
    }
  }
}

在表的視圖控制器中創建一個將String映射到UIImage的字典,並在cellForRowAtIndexPath函數中修改數據。 詹姆森Quave對這一發現非常問題一個很好的教程在這里 已更新為也使用新的Swift 1.2語法。

謝謝我固定像這樣:

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)")
        }
      })

    }
  }
}

您還可以創建一個UIImage擴展,如果您想為Swift 3提供更清潔的解決方案,只需在configureCellWith函數中調用async函數。

    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()
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM