Search code examples
iosobjective-casynchronouscompletion

How do I support/add a completion handler to my asynchronous method?


I am following this answer to test an asynchronous method I defined in a class. However I am unable to add a completion handler defintion to it. Any help?

I got a method defined as following:

//.h
- (void)loadData;

//.m   
 - (void)loadData{
        NSString *urlString =
    [NSString stringWithFormat:@"www.example.com/json", kResultsLimit ];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                           }
    }];

I would like now to add a completion handler to the loadData method definition.. how can I add it both in the .h and .m file?

example of .h:

        - (void)loadData+completionhandler;

Solution

  • @AdamPro13 gives you an example of how to do it.

    My guess is that you're struggling with how to define a method that takes a block as a parameter. It's confusing.

    I use this site (with a less SFW URL name) to figure out the syntax of using blocks in different situations:

    GoshDarnLinkSyntax

    The key bit for you is this part:

    Passing a block as a method parameter:

    - (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;