AFNetworking 2.0 AFHTTPSessionManager: how to get status code and response JSON in failure block?

后端 未结 7 805
你的背包
你的背包 2020-12-04 10:08

When switched to AFNetworking 2.0 the AFHTTPClient has been replaced by AFHTTPRequestOperationManager / AFHTTPSessionManager (as mentioned in the migration guide). The very

7条回答
  •  醉酒成梦
    2020-12-04 10:37

    After of read and research for several days, It worked for me:

    1) You have to build your own subclass of AFJSONResponseSerializer

    File : JSONResponseSerializerWithData.h:

    #import "AFURLResponseSerialization.h"
    
    /// NSError userInfo key that will contain response data
    static NSString * const JSONResponseSerializerWithDataKey = @"JSONResponseSerializerWithDataKey";
    
    @interface JSONResponseSerializerWithData : AFJSONResponseSerializer
    @end
    

    File: JSONResponseSerializerWithData.m

    #import "JSONResponseSerializerWithData.h"
    
    @implementation JSONResponseSerializerWithData
    
    - (id)responseObjectForResponse:(NSURLResponse *)response
                               data:(NSData *)data
                              error:(NSError *__autoreleasing *)error
    {
        id JSONObject = [super responseObjectForResponse:response data:data error:error];
        if (*error != nil) {
            NSMutableDictionary *userInfo = [(*error).userInfo mutableCopy];
            if (data == nil) {
    //          // NOTE: You might want to convert data to a string here too, up to you.
    //          userInfo[JSONResponseSerializerWithDataKey] = @"";
                userInfo[JSONResponseSerializerWithDataKey] = [NSData data];
            } else {
    //          // NOTE: You might want to convert data to a string here too, up to you.
    //          userInfo[JSONResponseSerializerWithDataKey] = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                userInfo[JSONResponseSerializerWithDataKey] = data;
            }
            NSError *newError = [NSError errorWithDomain:(*error).domain code:(*error).code userInfo:userInfo];
            (*error) = newError;
        }
    
        return (JSONObject);
    }
    

    2) Setup your own JSONResponseSerializer in your AFHTTPSessionManager

    + (instancetype)sharedManager
    {
        static CustomSharedManager *manager = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            manager = [[CustomSharedManager alloc] initWithBaseURL:<# your base URL #>];
    
            // *** Use our custom response serializer ***
            manager.responseSerializer = [JSONResponseSerializerWithData serializer];
        });
    
        return (manager);
    }
    

    Source: http://blog.gregfiumara.com/archives/239

提交回复
热议问题