我試圖解決在Swift中以TableView異步下載圖像的問題。這是我的問題:我從一個網址異步下載圖像,但如果我快速滾動TableView,我的圖片開始旋轉(圖像交替顯示,直到出現正確的圖像)。Swift Image下載TableView
這是我的下載異步代碼和imageCache
let imageCache = NSCache()
//DOWNLOAD Image ASINC
extension UIImageView {
public func imageFromServerURL(url: String){
if(imageCache.objectForKey(url) != nil){
self.image = imageCache.objectForKey(url) as? UIImage
}else{
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
if error == nil {
dispatch_async(dispatch_get_main_queue(), {() -> Void in
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: url)
self.image = downloadedImage
}
})
}
else {
print(error)
}
})
task.resume()
}
}
}
和我TableView中回憶起這樣:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("record_charts", forIndexPath: indexPath) as! myTableViewCell
let url_img = "https://image/download.jpg"
cell.immagine.imageFromServerURL(url_img)
return cell
}
檢查此問題:https://stackoverflow.com/questions/15668160/asynchronous-downloading-of-images-for-uitableview-with-gcd。 –
這是在對象c中,它不起作用... – mfiore
你可以從這個問題得到你的問題的一般概念。 –