mmattax
mmattax

Reputation: 27670

Need help desiging an API wrapper for iOS / iPhone application

I'm currently building an iPhone app that needs to connect to an API. I built an API class that makes an async web request and uses a delegate to get the response (on the main UI thread). It looks something like this:

Api* api = [[Api alloc] init]
api.delegate = self;
[api request:@"foo/bar"]; // makes async API call via NSURLConnection

-(void) apiRespondedWith(id) response
{
    // do stuff with API response.
}

This works well, but I'd like to make several API requests in a ViewController and would like an easier way to distinguish between the calls. Is there a way to have specific callbacks for each API call made? Selectors or blocks seem like a way to do this, but I'm unsure of the best way to implement this.

Upvotes: 0

Views: 485

Answers (1)

FluffulousChimp
FluffulousChimp

Reputation: 9185

There are several ways to accomplish this. For example, you could perform the web request in an NSOperation/NSOperationQueue. Note that if you use this approach the NSURLConnection will need to be performed synchronously inside the NSOperation - because the NSOperation is already executing asynchronously. Each web download request is encapsulated in an NSOperation which, in turn, is submitted to an NSOperationQueue.

You can check out an example of using NSOperation.

You could extend the example above by providing the NSOperation a completion block.

Alternatively, you could consider using a third-party library such as AFNetworking which uses this sort of blocks-based callback mechanism.

Upvotes: 1

Related Questions