Necesita ayuda para diseñar un contenedor de API para la aplicación iOS / iPhone

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.

preguntado el 09 de marzo de 12 a las 17:03

1 Respuestas

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 - porque el 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 ejemplo de uso 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.

respondido 09 mar '12, 17:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.