Swift:下载和显示图像的时间比正常时间长 5 倍

Swift: Downloading and displaying an image takes 5 times longer than it should

我正在使用 Google 图片 API 下载一张图片,然后显示给用户,代码运行如下:

        downloadImage { [weak self] image in
        if let strongSelf = self {
            if let image = image {
                strongSelf.mainImage.image = image
            }
        }
    }
}

func downloadImage(completion: UIImage? -> Void) {

    let url = NSURL(string: "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=anything")
    let request = NSURLRequest(URL: url!)


    NSURLConnection.sendAsynchronousRequest(request, queue: self.operationQueue) { [weak self] response, data, error in
        if let strongSelf = self {
            if error != nil || data == nil {
                println(error)
                completion(nil)
                return
            }

            var serializationError: NSError?
            if let go = NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments, error: &serializationError) as? [String: AnyObject] {
                let responseData = go["responseData"] as [String:AnyObject]
                let results = responseData["results"] as [[String:String]]
                let firstObject = results[0]
                var firstURL = firstObject["unescapedUrl"]!
                let theurl = NSURL(string: firstURL)
                let imageRequest = NSURLRequest(URL: theurl!)

                NSURLConnection.sendAsynchronousRequest(imageRequest, queue: strongSelf.operationQueue) { response, data, error in
                    if error != nil || data == nil {
                        println(error)
                        completion(nil)
                        return
                    }

                    if let image = UIImage(data: data!) {
                        completion(image)

                    } else {
                        completion(nil)
                    }
                }
            } else {
                println(serializationError)
                completion(nil)
            }
        }
    }

这基本上只是找到图像的 URL,然后下载图像并将 mainImage 设置为该图像。但是,在大多数情况下,mainImage 需要大约 20 或 30 秒才能显示下载的图像,即使我知道图像的下载速度必须比这快得多(如果我打印 url 找到并在我的浏览器中打开它,它会在 3 或 4 秒内完成,然后我会耐心等待 mainImage 在模拟器中显示它)。同样有趣的是,如果我保存 url,切换视图控制器并让新的视图控制器有一个加载 URL 图像的图像变量,它会立即完成(就像在我的浏览器),而主视图控制器仍未加载它。

我认为问题在于您没有更新主队列中的 UI。尝试这样称呼它:

        downloadImage { [weak self] image in
        if let strongSelf = self {
            if let image = image {
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    strongSelf.mainImage.image = image
                })
            }
        }
    }