I have Network layer class, which has method with URL request. Seems like this:
- (void)networkRequestWithError:(NSError *__strong *)responseError
andCompletion:(void (^)(NSData*))completion
{
NSURL *url = ...
NSURLSessionDataTask *dataTask = [NSURLSession.sharedSession
dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// *responseError = error; for real errors
*responseError = [NSError errorWithDomain:@"1"
code:1
userInfo:@{}];
completion(data);
}];
[dataTask resume];
}
@end
I create instance of this network layer in controller and I want to handle error in completion block:
__block NSError *responseError;
[self.networkService networkRequestWithError:&responseError
withCompletion:^(NSData*) {
if (responseError != nil) {
NSLog(@"%@",responseError.localizedDescription);
} else {
//Some action with data. No matter
}
}];
Problem: responseError has some value in dataTask completion scope (when I init it), but in my completion block in controller it always nil. I don't have any idea why.
This is an asynchronous method. Don’t set the response error by indirection. Do exactly what
dataTaskWithURLdoes: pass it as another parameter into the completion block.