0

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?

Fabio
  • 1,913
  • 5
  • 29
  • 53
  • Why not show the UIAlertController from the ViewController that calls `startTaskWithComponents` from 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 make `showAlertToViewController` a class method as well. Networking code shouldn't be coupled with presentation logic. – JKo Oct 26 '17 at 19:49
  • Or you could use a singleton, but I would avoid that. More info here on the class method/instance method issue your facing. https://stackoverflow.com/questions/2121880/call-instance-method-from-class-method – JKo Oct 26 '17 at 19:57
  • For the first comment isn't posible because is a class method. Also I need to pass a parameter a UIViewController to show the alertView in a particular UIViewController – Fabio Oct 26 '17 at 21:42

0 Answers0