-1

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;
Community
  • 1
  • 1
mm24
  • 9,280
  • 12
  • 75
  • 170
  • Just add it. What's the question? – matt Feb 12 '15 at 01:54
  • @matt I have really no idea how to add it in the .h and .m file.. especially the .m file.. do I need to write some code for it? – mm24 Feb 12 '15 at 01:56
  • 1
    I repeat: what's the problem? A completion handler is a block, exactly as in the code you have already shown. What don't you know how to do? – matt Feb 12 '15 at 02:10
  • You can just type it like the code you had posted. What's the issue? – Zigii Wong Feb 12 '15 at 02:13
  • There are many methods like what you want in iOS. Find it before asking. Exp: `+ [UIView animateWithDuration:animations:]` – Tony Feb 12 '15 at 02:43

2 Answers2

3

@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;
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • That's great. I am trying this out.. however I need to find some reference on how to invoke "blockName" inside the completion handler of the block defined in the function above. – mm24 Feb 12 '15 at 12:43
  • To call a block you use the same syntax as you use to invoke a function: `blockName(parameters)`, or just `blockName()` if it doesn't have any parameters. – Duncan C Feb 13 '15 at 03:30
1

Declare it in your .h like so: - (void)loadDataWithCompletion:(void(^)(id))completion;.

You can then call it in the completion handler of that network request with completion(data);

AdamPro13
  • 7,232
  • 2
  • 30
  • 28