要求:用AFNetworking 下载一张图片展示出来,或者请求json数据
pod一个最新的AFNetworking,然后想去download一张图片
然后发现下载不下来
错误一:
xcode控制台打印如下错误:
NSErrorFailingURLKey = "https://raw.githubusercontent.com/robinson911/robinson911.github.io/master/img/contact-bg.jpg";
NSLocalizedDescription = "Request failed: unacceptable content-type: image/jpeg";
错误分析:
content-type:是请求(request)/或者返回(response)数据的格式类型
从上边的提示可以看出需要设置的是请求content-type类型。
解决:设置一下数据格式类型
[manager.responseSerializersetAcceptableContentTypes:[NSSetsetWithObjects:@"image/png",@"image/jpeg",nil]];
重新rebuild,发现图片还是加载不出来
xcode控制台打印如下错误:
NSDebugDescription = "JSON text did not start with array or object and option to allow fragments not set.";
}----Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
然后看源码发现:
在默认情况下,afnetworking网络请求都是以json的数据格式返回数据,因此,客户端也会以json为默认格式,如果返回的数据为非json标准格式,则会出现上述错误。
只需要在发送请求前加入:manager.responseSerializer = [AFHTTPResponseSerializer serializer]
便可以解决这个问题了。
然后重新rebuild,发现图片加载正常了
编译通过请求到图片的源码如下:
- (void)requestNetData:(NSString*)url
{
NSSet *ljSet = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain",@"application/xml",@"text/xml",@"image/png",@"image/jpeg",nil];
AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//manager.requestSerializer = [AFJSONRequestSerializer serializer];
//manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.responseSerializer setAcceptableContentTypes:ljSet];
[manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
CHDebugLog(@"totalUnitCount:%lld---completedUnitCount:%lld",downloadProgress.totalUnitCount,downloadProgress.completedUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//CHDebugLog(@"%@",responseObject);
if ([url rangeOfString:@"png"].location != NSNotFound || [url rangeOfString:@"jpeg"].location != NSNotFound || [url rangeOfString:@"jpg"].location != NSNotFound) {
dispatchToMain(^{
UIImage *image = [UIImage imageWithData:responseObject];
self.LJImageView.image = image;
});
}
else if ([url rangeOfString:@"json"].location != NSNotFound)
{
/*NSError *error = nil;
1.需要将data转化为json
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
CHDebugLog(@"print json data----%@",dict);
*/
//2.初始化为 manager.responseSerializer = [AFJSONResponseSerializer serializer]; 来帮助你接收json数据
CHDebugLog(@"print json data----%@",responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
CHDebugLog(@"%@----%@",error.userInfo,error);
}];
}