【问题标题】:AFHTTPSessionManager - get unserialized/raw response body (NSData?)AFHTTPSessionManager - 获取非序列化/原始响应正文(NSData?)
【发布时间】:2015-04-10 22:12:03
【问题描述】:

我根据推荐的 iOS 8 最佳实践对 AFHTTPSessionManager 进行了子类化(代替了我之前使用的 AFHTTPOperationManager)。

我可以从task 中获取NSHTTPURLResponse(除了没有正文,只有标题),回调返回序列化的responseObject,这很好。

有时我需要将响应记录为字符串或将其显示在文本字段中 - 似乎没有办法在本机使用 SessionManager 来执行此操作? OperationManager 允许您将原始响应引用为 NSString:

operation.responseString;

我想我可以对序列化的 requestObject 进行字符串化,但这似乎有很多不必要的开销,并且如果响应对象是无效的 JSON 也无济于事。

这是我的子类单例:

@implementation MyAFHTTPSessionManager

+ (instancetype)sharedManager {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

然后制作一个简单的 GET(我已将其添加到块方法中),我可以这样做:

[[MyAFHTTPSessionManager sharedManager] GET:_url parameters:queryParams success:^(NSURLSessionDataTask *task, id responseObject) {
        completion(YES, task, responseObject, nil);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        completion(NO, task, nil, error);
    }];

【问题讨论】:

  • 不幸的是,这是基于 NSURLSession 的 AFNetworking API 的限制之一。这就是为什么我仍然使用NSURLConnection 版本,除了它基于NSOperation

标签: ios objective-c afnetworking-2


【解决方案1】:

您可以通过创建自定义响应序列化器来完成此操作,该序列化器记录数据并使用标准响应序列化器序列化响应,将原始数据和解析对象组合成自定义复合响应对象。

@interface ResponseWithRawData : NSObject
@property (nonatomic, retain) NSData *data;        
@property (nonatomic, retain) id object;
@end

@interface ResponseSerializerWithRawData : NSObject <AFURLResponseSerialization>
- (instancetype)initWithForwardingSerializer:(id<AFURLResponseSerialization>)forwardingSerializer;
@end

...

@implementation ResponseWithRawData
@end

@interface ResponseSerializerWithRawData ()
@property (nonatomic, retain) forwardingSerializer;
@end

@implementation ResponseSerializerWithRawData

- (instancetype)initWithForwardingSerializer:(id<AFURLResponseSerialization>)forwardingSerializer {
    self = [super init];
    if (self) {
        self.forwardingSerializer = forwardingSerializer;
    }
    return self;
}

- (id)responseObjectForResponse:(NSURLResponse *)response
                       data:(NSData *)data
                      error:(NSError *__autoreleasing *)error {
    id object = [self.forwardingSerializer responseObjectForResponse:response data:data error:error];
    // TODO: could just log the data here and then return object; so that none of the request handlers have to change
    if (*error) {
        // TODO: Create a new NSError object and add the data to the "userInfo"
        // TODO: OR ignore the error and return the response object with the raw data only
        return nil;
    } else {
        ResponseWithRawData *response = [[ResponseWithRawData alloc] init];
        response.data = data;
        response.object = object;
        return response;
    }
}

@end

然后在您的会话管理器上设置此序列化程序:

@implementation MyAFHTTPSessionManager

+ (instancetype)sharedManager {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        instance.responseSerializer = [[ResponseSerializerWithRawData alloc] initWithForwardingSerializer:instance.responseSerializer];
    });
    return instance;
}

现在在您的完成处理程序中,您将获得一个 ResponseWithRawData 实例:

[[MyAFHTTPSessionManager sharedManager] GET:_url parameters:queryParams success:^(NSURLSessionDataTask *task, id responseObject) {
    ResponseWithRawData *responseWithRawData = responseObject;
    NSLog(@"raw data: %@", responseWithRawData.data);
    // If UTF8 NSLog(@"raw data: %@", [[NSString alloc] initWithData:responseWithRawData.data encoding:NSUTF8StringEncoding]);
    // TODO: do something with parsed object
} failure:^(NSURLSessionDataTask *task, NSError *error) {

}];

我只是在没有编译/测试的情况下完成了这个,所以我将把它留给你调试和填补空白。

【讨论】:

    【解决方案2】:

    您可以使用“AFNetworkingOperationFailingURLResponseDataErrorKey”键直接从 AFNetworking 访问“数据”对象,因此无需对 AFJSONResponseSerializer 进行子类化。您可以将数据序列化为可读的字典。下面是一些获取 JSON 数据的示例代码:

    NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
     NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];
    

    这是在 Failur 块中获取状态码的代码

    NSHTTPURLResponse* r = (NSHTTPURLResponse*)task.response;
    NSLog( @"success: %d", r.statusCode ); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 2022-01-18
      相关资源
      最近更新 更多