gpt4 book ai didi

ios - 如何下载图像来填充我的 collectionviewcell JSON?

转载 作者:行者123 更新时间:2023-11-30 11:59:41 24 4
gpt4 key购买 nike

//Parsing JSON Oké
let parsedData : [String:AnyObject]
do{
parsedData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:AnyObject]
guard let results = parsedData["results"] as? [[String:AnyObject]] else {
print("There is a problem related to results fetch"); return }
for res in results {

var dataMi : Data!
//For the image data
let urlOfthePic = URL(string: "https://image.tmdb.org/t/p/w92\(res["backdrop_path"]!)")
let downLoadPicTask = URLSession.shared.dataTask(with: urlOfthePic!, completionHandler: { (data, res, err) in
guard let data = data else {print("second"); return}
dataMi = data
self.mov.movImage = UIImage(data: dataMi)!
print(dataMi)
});downLoadPicTask.resume()
print("2:", dataMi)
//Error is occured because of the "nil"
//self.mov.movImage = UIImage(data:dataMi)!

self.mov.movTitle = res["original_title"] as! String
self.mov.desctiption = res["overview"] as! String
self.movResult.append(self.mov)
self.resultCount = results.count
}
DispatchQueue.main.async() {
self.myCollectionView.reloadData()
}
}catch{
print("Error is occured because of the Json Serialization")
}
};task.resume()

Problem about the sequence of the downloading

此代码运行良好,但下载图像时存在问题,因为图像 url 取决于 json url。我想在下载其他数据(例如电影标题、电影描述等)时下载图像。

当代码运行时:

print(dataMi)

返回数据但是...

print("2:", dataMi) 

返回零。那么我该怎么做才能正确运行该部分呢? 因为它也会导致错误,所以我无法在单元格中设置我的 ImageView

 //Error is occured because of the "nil" 
//self.mov.movImage = UIImage(data:dataMi)!

Console Screen Shot

最佳答案

对于您的第一个问题,

let downLoadPicTask = URLSession.shared.dataTask(with: urlOfthePic!, completionHandler: { (data, res, err) in
guard let data = data else {print("second"); return}
dataMi = data
self.mov.movImage = UIImage(data: dataMi)!
print(dataMi)
});downLoadPicTask.resume()
print("2:", dataMi)

这段代码是异步运行的,所以print("2:", dataMi)将立即执行,但 print(dataMi)将在 dataTask 之后执行已完成。因此,如果您打印 dataMi立即,它将是 nil当然。之后dataTask完成,dataMi不是nil已包含数据。

对于您的第二个问题,请检查您的 urlOfthePic 是否是正确且可访问的。

关于ios - 如何下载图像来填充我的 collectionviewcell JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47398019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com