Search code examples
objective-cafhttprequestoperation

return data from AFHTTPRequestOperation?


I'm moving my app code to an MVC model and so I created a method to retrieve some data from an API.

+ (NSMutableArray *)loadFromFeed {
    NSString *feed = @"https://api.test.com";

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:feedUrl]];

    request = [mutableRequest copy];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [JSONResponseSerializerWithData serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *jsonArray = (NSArray *)[responseObject objectForKey:@"items"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        CLS_LOG(@"Error");
    }];
}

Now, ideally, I'd like to return jsonArray as part of this method. However, since AFHTTPRequestOperation is asynchronous, I don't know how to solve this and still be able to call [Data loadFromFeed]; anywhere in the app. How can I do this?


Solution

  • You could pass two block named success and failure to loadFromFeed , and then call the two block from your setCompletionBlockWithSuccess success and failure block, passing jsonArray to the success block:

    typedef void (^Success)(id data);
    typedef void (^Failure)(NSError *error);
    
    - (void)loadFromFeed:(Success)success failure:(Failure)failure;
    
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *jsonArray = (NSArray *)[responseObject objectForKey:@"items"];
        success?success(jsonArray):nil;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure?failure(error):nil;
    }];
    

    then use in this way:

    [Data loadFromFeed:^(id data) {
        NSLog(@"%@",data)
    } failure:^(NSError *error) {
        NSLog(@"%@",error)
    }];];