Swift:下载和显示图像需要5倍的时间

时间:2015-03-21 13:50:04

标签: swift uiimage nsurlconnection

我正在使用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设置为该图像。但是,在大多数情况下,显示下载的图像需要大约20或30秒的mainImage,即使我知道图像必须下载的速度要快得多(如果我打印了找到的网址并在我的浏览器中打开它,它会做它在3或4秒内,然后我会耐心地等待mainImage在模拟器中显示它)。有趣的是,如果我保存网址,切换视图控制器并让新的视图控制器有一个图像变量加载URL图像,它将直接做到(就像在我的浏览器中打开它)而主视图控制器仍然没有加载它。

1 个答案:

答案 0 :(得分:1)

我认为问题在于您没有更新主队列中的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
                })
            }
        }
    }