Parse JSON response with AFNetworking

后端 未结 4 1349
长情又很酷
长情又很酷 2020-12-09 19:18

I\'ve setup a JSON post with AFNetworking in Objective-C and am sending data to a server with the following code:

AFHTTPRequestOperationManager          


        
4条回答
  •  情深已故
    2020-12-09 19:54

    I find it works best to subclass AFHTTPClient like so:

    //  MyHTTPClient.h
    
    #import 
    
    @interface MyHTTPClient : AFHTTPClient
    
    + (instancetype)sharedClient;
    
    @end
    
    //  MyHTTPClient.m
    
    #import "MyHTTPClient.h"
    
    #import 
    
    static NSString *kBaseUrl = @"http://api.blah.com/yada/v1/";
    
    @implementation MyHTTPClient
    
    + (instancetype)sharedClient {
        static id instance;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[self alloc] init];
        });
        return instance;
    }
    
    - (id)init {
        if (self = [super initWithBaseURL:[NSURL URLWithString:kBaseUrl]]) {
            self.parameterEncoding = AFJSONParameterEncoding;
    
            [self setDefaultHeader:@"Accept" value:@"application/json"]; // So AFJSONRequestOperation becomes eligible for requests.
            [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; // So that it gets used for postPath etc.
        }
        return self;
    }
    
    @end
    

    The important bits are:

    • Setting the 'Accept' in such a way that AFJSONRequestOperation becomes eligible.
    • Adding AFJSONRequestOperation to the http operation classes.

    Then you can use it like so:

    #import "MyHTTPClient.h"
    
    @implementation UserService
    
    + (void)createUserWithEmail:(NSString *)email completion:(CreateUserCompletion)completion {
        NSDictionary *params = @{@"email": email};
        [[MyHTTPClient sharedClient] postPath:@"user" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
            completion([responseObject[@"userId"] intValue], YES);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            completion(0, NO);
        }];
    }
    
    @end
    

    The beauty of this is that your responseObject is automatically JSON-parsed into a dictionary (or array) for you. Very clean.

    (this is for afnetworking 1.x)

提交回复
热议问题