image - 下载图像 Swift

标签 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
        }


    })

我想使用的 URL 是这样的: 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

谢谢, 托拜厄斯

最佳答案

据我所知,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)
}

关于image - 下载图像 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24935677/

相关文章:

linux - 从pdf文件中提取矢量图像

javascript - 更新在新浏览器选项卡中打开的 pdf 的当前页码

java - Spring MVC 在一个请求中返回多个对象

javascript - 为什么 array.push 会覆盖整个数组?

PHP 裁剪图像以固定宽度和高度而不丢失尺寸比例

wordpress中用于图片上传的php代码

javascript - 检查提交的 URL 至少有一个子目录

javascript - 散列模式下的 Angular JS 链接行为不正确

python - 使用带有 python 请求库的 github 操作时出现 404 错误

c - 图像库和 gif 图像