Abel
Abel

Reputation: 315

Executing an AFHTTPOperation in background and return result

I'm currently working on an iOS App and i use AFNetworking to communicate with a distant API. What il'd like to do is make different functions that returns me the API response. My current code is:

-(void)requestMethod:(NSString *)method arguments:(id)arguments
{
    NSDictionary *parameters=@{@"jsonrpc": @"2.0", @"method": method, @"params": arguments};
   [httpClient postPath:methodPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error;
        NSDictionary *responseParsed=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];

}

Now this code is executed by blocks, that are called when i receive a response from the server. What is the best implementation of a function that when called on whatever thread would return me the response of a certain method ? Like:

-(NSArray *)getUsersFromAPI;

Thanks !

Upvotes: 2

Views: 430

Answers (1)

CodaFi
CodaFi

Reputation: 43330

You can make your method take a block with the resulting NSArray as a parameter, and pass it as an arg to the fetching function:

-(void)getUsersFromAPIWithResponse:(void(^)(AFHTTPRequestOperation *operation, NSArray *users))responseBlock {
    NSDictionary *parameters=@{};
    [httpClient postPath:methodPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error;
        NSArray *responseParsed = //do something cool;
        responseBlock(operation, responseParsed);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

Upvotes: 1

Related Questions