我正在尝试在cellForRowAtIndexPath
方法中检索这样的用户个人资料照片:
let profileImage = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://website.com/something/somethingelse-pic/\(self.userArray[indexPath.row]).jpg")!)!)
我只是想知道是否有更好更快的方法来做到这一点,因为这似乎加载得非常缓慢且滞后。
任何帮助都将不胜感激!!
答案 0 :(得分:0)
您可以使用async从网址加载图片
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[urlString] = image
// Update the cell
dispatch_async(dispatch_get_main_queue(), {
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView?.image = image
}
})
}
else {
// println("Error: \(error.localizedDescription)")
}
})
参考:http://jamesonquave.com/blog/developing-ios-apps-using-swift-part-5-async-image-loading-and-caching/