Reputation: 602
How can I return data when completionHandler finishes? I tried this method, but it shows an error:
- (NSData *)ReturnDataFromUrl{
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
return data;
}];
}
Upvotes: 0
Views: 1774
Reputation: 25687
When you say return data;
, you are actually trying to return data
to the caller of the completion block - which doesn't work.
Since you are using an asynchronous method, you can't return data received in a block back to the method you started the network operation in. By the time the code in that block is called, the system is long done with executing that method.
What you need to do instead is set up a delegate system - if this is a helper class, you could add a protocol including a method like didFinishLoadingStuff:(NSData *)stuff
.
You would then change
- (NSData *)ReturnDataFromURL{...}
To something like
- (void)getDataFromUrlWithDelegate:(NSObject<StuffGetterProtocol> *)delegate{...}
And instead of return data;
, you would say:
[delegate didFinishLoadingStuff:data];
And of course implement the delegate method in whatever class you are calling this from:
- (void)didFinishLoadingStuff:(NSData *)stuff
{
//do something with stuff
}
Upvotes: 4