来自URL的UIImage需要太多时间才能显示

时间:2018-07-16 22:53:07

标签: ios swift uiimageview uiimage lazy-loading

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

1 个答案:

答案 0 :(得分:0)

首先,您有2个嵌套请求

第二,您可以在while循环中加载这样的图像

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

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

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

DispatchQueue.main.async {

  // to set the images 
}