正在下载Image Swift

时间:2014-07-24 13:52:42

标签: image url request swift

我想从Facebook下载图像并将其存储到我的缓存中,我通过HTTPS调用它。如果我只使用HTTP一切正常,但如果我将其更改为HTTPS则不再有效。

这是我的代码:

// Grab the artworkUrl key to get an image URL for thumbnail
        var urlString: NSString = rowData["cover"] as NSString

        // Check our image cache for the existing key. This is just a dictionary of UIImages
        var image: UIImage? = self.imageCache.valueForKey(urlString) as? UIImage

        if( !image? ) {
            // If the image does not exist, we need to download it
            var imgURL: NSURL = NSURL(string: urlString)

            // Download an NSData representation of the image at the URL
            var request: NSURLRequest = NSURLRequest(URL: imgURL)

            var urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self)

            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in

                if !error? {

                    //var imgData: NSData = NSData(contentsOfURL: imgURL)
                    image = UIImage(data: data)

                    // Store the image in to our cache
                    self.imageCache.setValue(image, forKey: urlString)

                    cell.image = image


                    println(self.imageCache)

                }
                else {
                    println("Error: \(error.localizedDescription)")
                }
            })

        }
        else {
            cell.image = image
        }


    })

我想要使用的网址是: https://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-xpf1/t1.0-9/q71/s720x720/995054_485489274919674_7207866955460529362_n.jpg

错误是“超时”。

使用此URL一切正常: http://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-xpf1/t1.0-9/q71/s720x720/995054_485489274919674_7207866955460529362_n.jpg

谢谢, 托拜厄斯

1 个答案:

答案 0 :(得分:2)

据我所知,NSURLConnection有时会遇到HTTPS连接问题。尝试将这两种方法添加到您的课程中(并将其标记为NSURLConnectionDelegate)(来自this answer):

func connection(connection: NSURLConnection!, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace!) -> Bool  {
    return true
}

func connection(connection: NSURLConnection!, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge!) {
    challenge.sender.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust), forAuthenticationChallenge: challenge)
}