0

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?

user4486205
  • 105
  • 1
  • 7
  • You need to pass a completion to loadFromFeed and call the completion from your success block, passing jsonArray to the completion. – i_am_jorf May 27 '15 at 17:55

1 Answers1

2

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)
}];];
ChenYilong
  • 8,543
  • 9
  • 56
  • 84