Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking (AFJSONRequestOperation) convert to AFHTTPClient

I have the following code that works well but I need a little more control over it and especially need to start using the Reachability code in 0.9.

NSString *urlString = [NSString stringWithFormat:@"http://example.com/API/api.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    _self.mainDictionary = [JSON valueForKeyPath:@"elements"];
    [_self parseLiveData];
} failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON){
    //NSLog(@"Failed: %@",[error localizedDescription]);        
}];

if (operation !=nil && ([self.sharedQueue operationCount] == 0)) {
    [self.sharedQueue  addOperation:operation];
}

I am struggling to work out how I can convert this same code across to using an AFHTTPClient so that I can take advantage of the "setReachabilityStatusChangeBlock".

like image 768
Lee Armstrong Avatar asked Feb 23 '12 10:02

Lee Armstrong


1 Answers

Just create a subclass of AFHTTPClient with a singleton

+ (id)sharedHTTPClient
{
    static dispatch_once_t pred = 0;
    __strong static id __httpClient = nil;
    dispatch_once(&pred, ^{
        __httpClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"http://example.com/API"]];
        [__httpClient setParameterEncoding:AFJSONParameterEncoding];
        [__httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
    });
    return __httpClient;
}

And then call the getPath method

[[YourHTTPClient sharedHTTPClient]
   getPath:@"api.php"
   parameters:nil
      success:^(AFHTTPRequestOperation *operation, id JSON){
              _self.mainDictionary = [JSON valueForKeyPath:@"elements"];
              [_self parseLiveData];
      }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          //NSLog(@"Failed: %@",[error localizedDescription]); 
      }];
like image 145
Mathieu Hausherr Avatar answered Oct 24 '22 07:10

Mathieu Hausherr