I have this code it's a method class in a NSObject sub class.
+ (void)startTaskWithComponents:(NSURLComponents *)components
andHandler:(void (^)(NSDictionary* weatherData))handler {
NSURL *url = components.URL;
NSURLSession* session = [NSURLSession sharedSession];
NSURLSessionDataTask* task = [session dataTaskWithURL:url completionHandler:^(NSData* data, NSURLResponse * response, NSError* error) {
//TODO add error handler
if (!error) {
NSMutableDictionary *JSONData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
handler( JSONData );
}else{
// I need to show passing the error to the method showAlertToViewController but is inaccesible :(
}
}];
[task resume];
}
- (void)showAlertToViewController:(UIViewController *) controller withError:(NSError*)error {
UIAlertController *alert = [UIAlertController
alertControllerWithTitle:@"Warning"
message:[error localizedDescription]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okButton = [UIAlertAction
actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil];
[alert addAction:okButton];
[controller presentViewController:alert animated:YES completion:nil];
}
And the problem its when I try to handle the error I have this code to show the error in the ViewController suitable
How can handle this situation to show the alert in the ViewController to the user?
startTaskWithComponentsfrom the completion block? You can pass the error thru the completion block. You can't access an instance method from a class method like this, unless you makeshowAlertToViewControllera class method as well. Networking code shouldn't be coupled with presentation logic.