我具有带有图像和标签的集合视图。我能够在集合视图中非常缓慢地加载图像和标签值,这意味着集合视图需要花费大量时间来下载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图像。
第一