URL中的UIImage显示时间过长



我正在尝试从URL加载图像。加载工作正常,但图像显示时间过长。有时,我需要在选项卡之间切换(使用选项卡栏控制器(来查看新闻图像。所以,我正在寻找一种方法来加快它加载到imageview。

let discoverTask = URLSession.shared.dataTask(with: discoverUrl!) { (data, response, error) in
if error != nil {
print(error as Any)
} else {
let jsonString: String = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)! as String
if let data = jsonString.data(using: .utf8) {
if let json = try? JSON(data: data) {
for item in json["results"].arrayValue {
posterURLString = posterBaseURL + item["poster_path"].stringValue
discoverPosters.append(posterURLString)
}
var i = 0
while(i < discoverPosters.count)
{
let posterURL = URL(string: discoverPosters[i])!
discoverPostersData.append(try! Data(contentsOf: posterURL))
i = i+1
}
//I'm setting the new picture from the URL
let toDiscoverPoster1 = UIImage(data: discoverPostersData[0])
UIView.transition(with: self.discoverPoster1,
duration:1,
options: .transitionCrossDissolve,
animations: { self.discoverPoster1.image = toDiscoverPoster1 },
completion: nil)
let toDiscoverPoster2 = UIImage(data: discoverPostersData[1])
UIView.transition(with: self.discoverPoster2,
duration:1,
options: .transitionCrossDissolve,
animations: { self.discoverPoster2.image = toDiscoverPoster2 },
completion: nil)
let toDiscoverPoster3 = UIImage(data: discoverPostersData[2])
UIView.transition(with: self.discoverPoster3,
duration:1,
options: .transitionCrossDissolve,
animations: { self.discoverPoster3.image = toDiscoverPoster3 },
completion: nil)
}
}
}
}

PS:对不起我英语不好。。。

首先您有两个嵌套的请求

第二次在一段时间的循环中加载这样的图像

discoverPostersData.append(try! Data(contentsOf: posterURL))

这不是一个好方法,因为它阻塞了主线程,您必须在后台队列中异步加载它们

第三个URLSession.shared.dataTask的完成在后台队列中运行,因此在将图像设置为UIImageViews 时需要使用

DispatchQueue.main.async {
// to set the images 
}

最新更新