来自 URL 的 UIImage 显示时间过长

UIImage from URL take too much time to appear

我正在尝试从 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 : 抱歉我的英语不好...

首先 你有 2 个嵌套请求

其次 你在 while 循环中像这样加载图像

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

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

第三完成URLSession.shared.dataTask在后台队列中运行,所以需要在给UIImageViews设置图片时使用

DispatchQueue.main.async {

  // to set the images 
}