I have a method which send request to server and i have created the call to that function with completionHandler as follows:
-(void)sendAddSubscriptionRequest:(NSString*)owner withComppletionHandler:(void (^)(BOOL, NSArray *, NSError *))completion
dataWebService = [[NSMutableData alloc] init];
NSURL* aUrl = [NSURL
URLWithString:[NSString stringWithFormat:@"https://www.google.com/add?"]];
NSMutableURLRequest* request =
[NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request addValue:[NSString stringWithFormat:@"Bearer %@", "token"]
forHTTPHeaderField:@"Authorization"];
[request setHTTPMethod:@"POST"];
NSString* postData =
[[NSString alloc] initWithFormat:@"owner=%@",
owner];
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
NSData* returnData = [NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
};
My problem is how should i return completion handler to my function after the data is fetched.
Thanks,.
As you are sending an asynchronous request, the method will return immediately as the data will be "returned" in the NSURLConnection
completion handler. You can then decode it there and pass it along to your own completion handler:
[NSURLConnection sendAsynchronousRequest:request
queue:nil
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSArray *array = nil;
if (!connectionError)
array = /* get from data somehow */
completion(!connectionError, array, connectionError);
}];
Note: It's not clear what your completion handler parameters mean, so I might have taken some liberties.