如何加快图像下载速度

时间:2016-10-14 18:49:09

标签: ios swift

我有一个循环,它接受了imageUrls数组并从中制作了图像,但它很慢,有没有办法加速它?

看起来像这样:

self.urlArray.forEach() { 
    let photoURL = URL(string: $0)
    guard let url = photoURL else {continue}
    let data = try? Data(contentsOf: url)
    guard let dataSafe = data else {continue}
    let finishedImage = UIImage(data: dataSafe)
    self.imagesArray.append(finishedImage)
}

1 个答案:

答案 0 :(得分:0)

您可以在后台线程中获取数据,然后在主线程上更新UIImageView。

let photoURL = URL(string: $0)
guard let url = photoURL else {continue}
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async{
    //fetch the image data in background
    let data = try? Data(contentsOf: url)
    guard let dataSafe = data else {continue}
    DispatchQueue.main.sync {
        //get back to main thread
        let finishedImage = UIImage(data: dataSafe)
        self.imagesArray.append(finishedImage)
    }
}