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?

3
  • 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. Commented Oct 26, 2017 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. stackoverflow.com/questions/2121880/… Commented Oct 26, 2017 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 Commented Oct 26, 2017 at 21:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.