Swift iOS8异步映像
我需要将图像缓存在iOS 8上的Swift中。我有一个自定义的表格单元格视图 这是我的密码:Swift iOS8异步映像,ios,swift,ios8,Ios,Swift,Ios8,我需要将图像缓存在iOS 8上的Swift中。我有一个自定义的表格单元格视图 这是我的密码: import UIKit class WorksTableViewCell: UITableViewCell { @IBOutlet var workImage: UIImageView! @IBOutlet var workTitle: UILabel! @IBOutlet var workDescription: UILabel! func configureCellWith(w
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
}
}
}
}
在表的视图控制器中创建一个将字符串映射到UIImage的字典,并在CellForRowatingIndexPath函数中修改数据。詹姆逊·奎夫(Jameson 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)")
}
})
}
}
}
如果希望为Swift 3提供更干净的解决方案,还可以创建UIImage扩展,并在configureCellWith函数中调用异步函数
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()
}
}