I find it works best to subclass AFHTTPClient like so:
// MyHTTPClient.h
#import <AFNetworking/AFHTTPClient.h>
@interface MyHTTPClient : AFHTTPClient
+ (instancetype)sharedClient;
@end
// MyHTTPClient.m
#import "MyHTTPClient.h"
#import <AFNetworking/AFJSONRequestOperation.h>
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)