[英]Asynchronously Load Images in UITableView While Downloading
我想知道是否有任何方法可以在下載項目時繼續重新加載tableView。
有圖像和與這些圖像相關的信息。 用戶首次打開該應用程序時,該應用程序開始使用HTTP下載圖像和數據。 如果他/她不斷離開viewController並返回到它,則用戶只能在tableView中看到正在下載的已下載項。
我試圖做這樣的事情:
while downloading {
tableView.reloadData()
}
,但是,這會占用過多內存,並且會使應用程序崩潰。
如何在下載圖像和數據的同時仍然保留在tableViewController中,以異步方式填充tableView?
PS:如果您對我使用的庫或API感興趣,可以使用Alamofire進行下載,並使用Realm進行數據持久化。
正確且常用的方法是將數據重新加載到表中,而不是委派單個單元格從鏈接異步加載圖像。
您可以迅速擴展UIImage
extension UIImageView {
func imageFromUrl(urlString: String) {
if let url = NSURL(string: urlString) {
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
if let imageData = data as NSData? {
self.image = UIImage(data: imageData)
}
}
}
}
}
然后在您的CellForRowAtIndexPath中使用類似這樣的方法從鏈接加載圖像
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
...
cell.image.imageFromUrl(dataArray[indexPath.row].imageUrl)
return cell
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.