2015-04-20 75 views
0

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

這裏是我的代碼:

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

回答

0

創建一個字典映射一個字符串表中的視圖控制器一個UIImage,並在功能的cellForRowAtIndexPath修改數據。 Jameson Quave在發現的這個問題上有一個很好的教程here。它已更新爲使用新的Swift 1.2語法。

0

感謝我定這樣的:

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

    } 
    } 
} 
0

您還可以創建一個UIImage擴展並調用異步函數在configureCellWith功能,如果你想爲雨燕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() 
    } 
} 
一個清潔的解決方案