AFHTTPSessionManager - get unserialized/raw response body (NSData?)

我的梦境 提交于 2019-12-05 14:15:09

You can accomplish this by creating a custom response serializer that records the data and serializes the response using the standard response serializer, combining both the raw data and parsed object into a custom, compound response object.

@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

Then set this serializer on your session manager:

@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;
}

Now in your completion handler you will get an instance of 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) {

}];

I just whipped this up without compiling/testing, so I will leave it to you to debug and fill in the gaps.

You can access the “data” object directly from AFNetworking by using the “AFNetworkingOperationFailingURLResponseDataErrorKey” key so there is no need for subclassing the AFJSONResponseSerializer. You can the serialize the data into a readable dictionary. Here is some sample code to get JSON Data :

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

Here is code to Get Status code in Failur block

NSHTTPURLResponse* r = (NSHTTPURLResponse*)task.response;
NSLog( @"success: %d", r.statusCode ); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!