如何在方法类中使用UIAlertController处理错误? (目标c)

时间:2017-10-26 16:50:55

标签: objective-c error-handling uialertcontroller class-method

我有这个代码,它是NSObject子类中的方法类。

+ (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];
}

问题是当我尝试处理错误时我有这段代码来显示ViewController中的错误

如何处理这种情况以向用户显示ViewController中的警报?

0 个答案:

没有答案