如何在 swift 中更快地加载 CollectionView 中的 JSON 图像 URL



>我有带有图像和标签的集合视图.. 我能够在集合视图中非常缓慢地加载图像和标签值我的意思是集合视图需要很多时间来下载 JSON img URL.. 但是我需要更快地从 JSON 下载到集合视图...而且我没有得到快速的 10 张图像相同..我不知道为什么会这样发生..任何人请帮助我在集合视图中下载 JSON IMG URL,下载速度更快。

这是我的代码:

import UIKit
struct JsonData {
var iconHome: String?
var typeName: String?
init(icon: String, tpe: String) {
self.iconHome = icon
self.typeName = tpe
}
}
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {
@IBOutlet weak var collectionView: UICollectionView!
var itemsArray = [JsonData]()
var idArray = [Int]()
var homSe = [JsonDataHome]()
override func viewDidLoad() {
super.viewDidLoad()
homeServiceCall()
//Do any additional setup after loading the view.
collectionView.delegate = self
collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell
let aData = itemsArray[indexPath.row]
cell.paymentLabel.text = aData.typeName
if let url = NSURL(string: aData.iconHome ?? "") {
if let data = NSData(contentsOf: url as URL) {
cell.paymentImage.image = UIImage(data: data as Data)
}
}
return cell
}
//MARK:- Service-call
func homeServiceCall(){
let urlStr = "https://dev.com/webservices"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
guard error == nil else {
print("error")
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
//print("the home json is (jsonObj)")
let financerArray = jsonObj["financer"] as! [[String: Any]]
for financer in financerArray {
let id = financer["id"] as? Int
let pic = financer["icon"] as? String
let typeName = financer["tpe"] as! String
self.idArray.append(id ?? 1)
self.itemsArray.append(JsonData(icon: pic ?? "", tpe: typeName))
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
}

在这里,我需要在集合视图中快速下载 JSON 图像。

首先,没有比里面的东西更快homeServiceCall()这取决于您的互联网连接

第二

if let data = NSData(contentsOf: url as URL) {

滚动时阻塞主线程并导致多次重新下载同一图像,使用SDWebImage获得单个异步下载和缓存的好处

import SDWebImage 
cell.paymentImage.sd_setImage(with: URL(string:aData.iconHome ?? ""), placeholderImage: UIImage(named: "placeholder.png"))

最新更新