ios - 无法使用 AFNetworking 3 为 JSON 和 XML 响应创建单例

标签 ios json xml afnetworking response

您好,我正在为 JSON 和 XML 响应创建一个网络单例

我的 ApiClient.h

+ (ApiClient *)sharedInstance;

-(instancetype)initWithBaseURL:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration;

我的 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 1 次。但是当再次调用再次解析时)(成功解析 XML 后)结果将无法正确解析(给出十六进制字符串响应)

我的 JSON block 请求

- (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 block 请求

- (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];
}

我的十六进制字符串失败响应: enter image description here

无论如何要使单例正常工作,或者我需要为 JSON 和 XML 响应制作 2 个单例?非常感谢任何帮助。谢谢!

最佳答案

您的错误很可能告诉您它期待 application/xmlContent-Type,而您可能有一个 application/json。很难说,因为您没有分享完整的错误,但很可能是这样。

有两种合乎逻辑的方法。要么:

  1. 让单个 AFHTTPSessionManager 接受 XML 和 JSON。因此,使用 AFHTTPResponseSerializerresponseSerializerapplication/xmlapplication/json 的 acceptableContentTypes (或您的两个 Web 服务返回的任何特定 Content-Type),然后当您收到 NSData 响应对象时,根据需要解析 XML 或 JSON .

  2. 有单独的 AFHTTPSessionManager 对象,一个用于 XML(使用 AFXMLResponseSerializerresponseSerializer),一个用于 JSON(使用 AFJSONResponseSerializer 的 responseSerializer)。请注意,如果您这样做,您根本不需要调整 acceptableContentTypes

关于ios - 无法使用 AFNetworking 3 为 JSON 和 XML 响应创建单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39035982/

相关文章:

php - 如何使用 php 将 .xlsx 文件转换为 .xml 文件?

ruby-on-rails - ebay BulkDataExchangeRequests API XML - 缺少 UUID

ios - 无法更改 Config.xml 中的 NSCameraUsageDescription

iphone - 在应用程序购买测试帐户不能在 IOS 中工作?

asp.net - .Net Core 标记助手智能感知和颜色编码不起作用

javascript - 在数组 Node.js 中组合 JSON 数组

ios - 如何通过 Facebook 广告点击将 IDFA 发送到 Google Analytics?

ios - 自定义选择器可以访问选项值,而不仅仅是选定的索引

javascript - Bloodhound,预取保存在我的文件中的 json 文件

php - 无法从字符串解析 XML