来自URL的图像请求失败

时间:2014-11-18 20:56:19

标签: ios swift uiimage

我有以下代码:

func getImage(urlString: String, completionHandler: UIImage -> Void) -> NSURLSessionTask {

    let request = NSMutableURLRequest(URL: NSURL(fileURLWithPath: urlString)!)

    println("Executing image request: \(urlString)")

    return session.dataTaskWithRequest(request) {
        data, response, error in
        if error != nil {
            println("\tGET request failed: \(error!)")
        } else {
            println("\tGET request succeeded!")
            let response = response as NSHTTPURLResponse
            if response.statusCode == 200 {
                let image = UIImage(data: data)
                dispatch_async(dispatch_get_main_queue()) { // dispatch naar main thread (main_queue is thread# van main thread van app)
                    completionHandler(image!)
                }
            }
        }
    }
}

但是当我执行它时,我得到以下输出:

Executing image request: http://i.imgur.com/rfw7jrU.gif
GET request failed: Error Domain=NSURLErrorDomain Code=-1100 
"The operation couldn’t be completed. (NSURLErrorDomain error -1100.)" 
UserInfo=0x14e9b200 {NSErrorFailingURLKey=file:///http:/i.imgur.com/rfw7jrU.gif,
NSErrorFailingURLStringKey=file:///http:/i.imgur.com/rfw7jrU.gif,
NSUnderlyingError=0x14d8d600 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1100.)"}

我不知道为什么会发生这种情况,因为我几乎完全相同的代码可以获得.json文件。我已经在我的设备和模拟器上测试了这个。

这在所有网址上都失败了,不仅仅是imgur链接。在我把它放入UIImage之前它也崩溃了,所以这也不是问题。

1 个答案:

答案 0 :(得分:6)

从错误消息中可以看到您的网址是文件网址

file:///http:/i.imgur.com/rfw7jrU.gif

且错误-1100kCFURLErrorFileDoesNotExist(请参阅CFNetwork Error Codes Reference)。

你应该替换

NSURL(fileURLWithPath: urlString)

通过

NSURL(string: urlString)
// Swift 3+:
URL(string: urlString)