AFHTTPSessionManager - get unserialized / unprocessed response (NSData?)

I subclassed the AFHTTPSessionManager according to the best practice for iOS 8 (instead of the AFHTTPOperationManager that I used before).

I can grab NSHTTPURLResponsefrom task(except that it has no body, only headers), and the callback returns serialized responseObject, which is good.

Sometimes I need to write a response as a string or display it in a text box - is there no way to do this initially using SessionManager? OperationManager allowed you to refer to the original response as an NSString:

operation.responseString;

I suppose I could compress the serialized requestObject, but this seems like a lot of extra overhead and won't help if the response object is not valid JSON.

Here is my subclass singleton:

@implementation MyAFHTTPSessionManager

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

And then, to make a simple GET (which I added to the block method), I can do:

[[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);
    }];
+4
source share
2 answers

This can be done by creating a custom response serializer that records data and serializes the response using a standard response serializer, combining both raw data and the analyzed object into a custom composite 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 install this serializer in the 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;
}

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) {

}];

/, .

+4

"" AFNetworking "AFNetworkingOperationFailingURLResponseDataErrorKey", 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 ); 
+2

All Articles