我有以下代码:
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 文件的几乎相同的代码确实有效。我已经在我的设备和模拟器上对此进行了测试。
这在所有 url 上都失败,不仅是 imgur 链接。在我将它放入 UIImage
之前它也会崩溃,所以这也不是问题所在。
最佳答案
从错误消息中可以看出您的 URL 是一个文件 URL:
file:///http:/i.imgur.com/rfw7jrU.gif
错误 -1100
是 kCFURLErrorFileDoesNotExist
(参见 CFNetwork Error Codes Reference)。
你应该替换
NSURL(fileURLWithPath: urlString)
通过
NSURL(string: urlString)
// Swift 3+:
URL(string: urlString)
关于ios - 来自 URL 的图像请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27003861/