我一直在尝试从 url 下载图像(更准确地说是 Craigslist)
首先,我使用了 SDWebImage 框架,但看不到图像。之后我尝试了一种简单的方法来下载网址:
使用此网址获取图片:
http://images.craigslist.org/01212_fxFfHsZFhoi_600x450.jpg
UIImageView image;
NSString *urlstring = [NSString stringWithFormat:@"http://images.craigslist.org/01212_fxFfHsZFhoi_600x450.jpg"];
NSURL *url = [NSURL URLWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[image setImageWithURLRequest:request
placeholderImage:[UIImage imageNamed:@"placeholder.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
// Succes on loading image
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
// Fail to load image
}];
我仍然无法在我的 ImageView 中看到图像。
问题是,如果我更改 url 并使用相同的确切代码,图像将被很好地下载。我试图在 Safari 中加载图像,它工作得很好,所以链接没问题。
例如我用过:
http://monsieurstolli.files.wordpress.com/2013/10/meh.jpg
它有效。
我不知道如何下载该图像。
编辑:
我做了更多调查并更改了代码:
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
requestOperation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Response: %@", responseObject);
_imga.image = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Image error: %@", error);
}];
[requestOperation start];
}
但这次我收到以下错误:
2014-10-16 15:07:10.537 CraigslistChecker[3192:907] Image error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: not found (404)" UserInfo=0x1c5b8e30 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x1c59ac60>, NSErrorFailingURLKey=images.craigslist.org/00W0W_blCL2sqk1Jt_600x450.jpg, NSLocalizedDescription=Request failed: not found (404), com.alamofire.serialization.response.error.data=<0d0a>}
purgeIdleCellConnections: found one to purge conn = 0x1c59b1f0
最佳答案
当我在网络浏览器中请求时,您发布的 URL 返回 404(未找到)错误,这意味着服务器拒绝为您提供 URL。所以要么:
我的猜测是最后一个。如果是这样,将 NSURLRequest 上的“Referer”(故意拼写错误) header 字段设置为包含相关图像的页面的 URL 应该可以解决问题,但您可能应该检查 Craigslist 以确保这样做不会违反他们的服务条款。否则,他们很有可能会将您应用的用户代理字符串列入黑名单。
关于ios - 从 Craigslist 下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26403399/