DJH DJH - 1 year ago 96
Objective-C Question

iOS async http call and delegates

I'm struggling here and I hope you can help. I am wanting to create a class where all of my webservice calls out are located. I want all of the calls async. The question I have is how to return the data back if it is async. I would assume that I would need to use a delegate, however I am not sure how to write it.

Thanks in advanced!

Answer Source

If you are going to write a class through which all of your HTTP calls are requested, blocks are the way to go. If you choose to use delegates your code will be scattered. You can implement as below :

@interface WebServiceManager : NSObject

- (void) dataForUser:(NSString*) userId withCompletionHandler:(void(^)(id userData)) onComplete;

@implementation WebServiceManager

- (void) dataForUser:(NSString*) userId withCompletionHandler:(void(^)(id userData)) onComplete {
    // Use NSURLConnection sendAsynchronousRequest OR AFHTTP Class
    // to make HTTP Calls
    // assume id data as data retreived from service.
    onComplete(data); // Return Data

From your model classes you can instantiate an object of WebServiceManager class and use as below:

// Model Class

- (void) getUserInfo {
    WebServiceManager *webSvc = [[WebServiceManager alloc] init];
    [webSvc dataForUser:@"foo" withCompletionHandler:^(id response) {
        // response is the data returned from HTTP async call.
        // do something with response now.
// With Blocks your code for requesting data and processing data will be one place now.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download