无法使用AFNetworking 3进行JSON和XML响应的单例 [英] Cannot make singleton for JSON and XML response using AFNetworking 3
问题描述
我正在为网络建立JSON和XML响应
Hi I'm Making a singleton for networking for JSON and XML response
我的ApiClient.h
my ApiClient.h
+ (ApiClient *)sharedInstance;
-(instancetype)initWithBaseURL:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration;
我的ApiClient.m
My ApiClient.m
+ (ApiClient *)sharedInstance {
static ApiClient *sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:SINGPOST_BASE_URL] sessionConfiguration:sessionConfiguration];
[sharedInstance setDataTaskWillCacheResponseBlock:^NSCachedURLResponse *(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse)
{
NSHTTPURLResponse *resp = (NSHTTPURLResponse*)proposedResponse.response;
NSMutableDictionary *newHeaders = [[resp allHeaderFields] mutableCopy];
if (newHeaders[@"Cache-Control"] == nil) {
newHeaders[@"Cache-Control"] = @"max-age=120, public";
}
NSURLResponse *response2 = [[NSHTTPURLResponse alloc] initWithURL:resp.URL statusCode:resp.statusCode HTTPVersion:nil headerFields:newHeaders];
NSCachedURLResponse *cachedResponse2 = [[NSCachedURLResponse alloc] initWithResponse:response2
data:[proposedResponse data]
userInfo:[proposedResponse userInfo]
storagePolicy:NSURLCacheStorageAllowed];
return cachedResponse2;
}];
});
return sharedInstance;
}
-(instancetype)initWithBaseURL:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration {
self = [super initWithBaseURL:url sessionConfiguration:configuration];
if (self) {
}
return self;
}
问题是单例无法同时处理XML和JSON响应.它可以成功解析JSON和XML一次.但是当再次调用以再次解析时(成功解析XML之后),结果将无法正确解析(给出十六进制字符串响应)
The problem is the singleton cannot handle both XML and JSON response. It can successfully parse the JSON and XML for 1 time. But when call again to parse again) (after successfully parse XML) result will not be parse properly (give hex string response)
我的JSON阻止请求
- (void)sendJSONRequest:(NSMutableURLRequest *)request
success:(void (^)(NSURLResponse *response, id responseObject))success
failure:(void (^)(NSError *error))failure {
self.responseSerializer.acceptableContentTypes = [AFHTTPResponseSerializer serializer].acceptableContentTypes;
NSURLSessionDataTask *dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error URL: %@",request.URL.absoluteString);
NSLog(@"Error: %@", error);
failure(error);
} else {
NSDictionary *jsonDict = (NSDictionary *) responseObject;
success(response,jsonDict);
NSLog(@"Success URL: %@",request.URL.absoluteString);
NSLog(@"Success %@",jsonDict);
}
}];
[dataTask resume];
}
我的XML阻止请求
- (void)sendXMLRequest:(NSMutableURLRequest *)request
success:(void (^)(NSURLResponse *response, RXMLElement *responseObject))success
failure:(void (^)(NSError *error))failure {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
self.responseSerializer = [AFHTTPResponseSerializer serializer];
[self.responseSerializer.acceptableContentTypes setByAddingObject:@"application/xml"];
NSURLSessionDataTask *dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error URL: %@",request.URL.absoluteString);
NSLog(@"Error: %@", error);
failure(error);
} else {
RXMLElement *rootXml = [RXMLElement elementFromXMLData:responseObject];
success(response, rootXml);
NSLog(@"Success URL: %@",request.URL.absoluteString);
NSLog(@"Success %@",rootXml);
}
}];
[dataTask resume];
}
我的十六进制字符串失败共鸣:
My hex string fail resonse:
无论如何要使单例正常工作,还是需要为JSON和XML响应设置2个单例?任何帮助都将不胜感激.谢谢!
Anyway to make the singleton work properly or I need to make 2 singleton for JSON and XML response? Any help is much appreciate. Thanks!
推荐答案
您的错误可能告诉您,它期望Content-Type
为application/xml
,而您可能拥有application/json
.很难说出来,因为您没有分享完整的错误,但是很可能是这样的.
Your error is likely telling you that it was expecting a Content-Type
of application/xml
, and you may of had an application/json
. It's hard to tell because you didn't share the full error, but it's likely something like that.
有两种逻辑方法.要么
-
只有一个
AFHTTPSessionManager
接受XML和JSON.因此,使用AFHTTPResponseSerializer
的responseSerializer
以及application/xml
和application/json
的acceptableContentTypes
(或者两个Web服务返回的特定特定Content-Type
),然后在收到NSData
响应对象时,可以根据需要解析XML或JSON.
Have single
AFHTTPSessionManager
accept both XML and JSON. So, with aresponseSerializer
ofAFHTTPResponseSerializer
and anacceptableContentTypes
of bothapplication/xml
andapplication/json
(or whatever specificContent-Type
your two web services return), and then when you receive theNSData
response object, either parse the XML or JSON as appropriate.
具有单独的AFHTTPSessionManager
对象,一个用于XML(AFXMLResponseSerializer
的responseSerializer
)和一个用于JSON(AFJSONResponseSerializer
的responseSerializer
)的对象.请注意,如果您这样做,则完全不需要调整acceptableContentTypes
.
Have separate AFHTTPSessionManager
objects, one for XML (with responseSerializer
of AFXMLResponseSerializer
) and one for JSON (with responseSerializer
of AFJSONResponseSerializer
). Note, if you do this, you don't have to adjust acceptableContentTypes
at all.
这篇关于无法使用AFNetworking 3进行JSON和XML响应的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!