0

I'm writing a method to consume data from the web-service. I wrote this method inside a class(common class), so I can use this class in any viewController to consume data. Inside this method, I check for the internet connection. If some failure occurs, I want to display an alert with the error description. This is my code inside my method:

 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{

        mainSession = [NSURLSession sharedSession];
        mainDataTask = [mainSession dataTaskWithRequest:MainRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            if (error) {
                UIAlertController *alertOne = [UIAlertController alertControllerWithTitle:@"Something Wrong!" message:[error description] preferredStyle:UIAlertControllerStyleAlert];
                // I want to show alert here 
            }
        }];

    });

This method is in my common class(NSObject). If something wrong with the connection, inside this block I want to show the error. How can I do that?

NSPratik
  • 4,714
  • 7
  • 51
  • 81
Jobs
  • 269
  • 2
  • 6
  • 21
  • you run that code ? and what is problem in above code? what will the output of the code? please tell me or update your question – Birendra Dec 29 '15 at 07:59
  • inside your NSObject class there's no viewController, thus u cant show the alert there, either return the alertView then show it in the VC, or use `UIWindow` extension to get the current VC then show it there – Tj3n Dec 29 '15 at 08:00

5 Answers5

0

#import <UIKit/UIKit.h> in your NSObject Class

then you can use UIAlertController.

UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"Title" message:nil preferredStyle:UIAlertControllerStyleAlert];
//...
id rootViewController=[UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
   rootViewController=[((UINavigationController *)rootViewController).viewControllers objectAtIndex:0];
}
[rootViewController presentViewController:alertController animated:YES completion:nil];
Divyanshu Sharma
  • 551
  • 2
  • 12
0

Do your AlertController declaration in main queue like this

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{

        mainSession = [NSURLSession sharedSession];
        mainDataTask = [mainSession dataTaskWithRequest:MainRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            if (error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertController *alertOne = [UIAlertController alertControllerWithTitle:@"Something Wrong!" message:[error description] preferredStyle:UIAlertControllerStyleAlert];
                    // I want to show alert here
                }); 
            }
        }];

    });
Arun
  • 1,391
  • 1
  • 10
  • 29
0

Use the following code. I hope it will be helpful to you

//Calling method

        [self showMessage:@"There is no internet connection for this device"
           withTitle:@"Error"];

//Write Method like

#pragma mark
#pragma mark -- UIAlertView Method
-(void)showMessage:(NSString*)message withTitle:(NSString *)title{
dispatch_async(dispatch_get_main_queue(), ^{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }]];

    [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:^{
    }];
});
}
Mannam Brahmam
  • 2,225
  • 2
  • 24
  • 36
0

How To Present An Alert View Using UIAlertController When You Don't Have A View Controller. Description.

Yes, you can only use UIAlertController only in UIViewController classes. So how can we do it in NSObject classes. If you see the description link given above you will get to the answer. To summarise in a line for the above description: Create a new window above the the current window. This new window will be our viewController where we display alert. So using this viewController you can call the method [presentViewController: animated: completion:].

dispatch_async(dispatch_get_main_queue(), ^{

                    UIWindow* window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

                    window.rootViewController = [UIViewController new];

                    window.windowLevel = UIWindowLevelAlert + 1;



                    NSString *msg=@“Your mssg";

                    UIAlertController* alertCtrl = [UIAlertController alertControllerWithTitle:@“Title" message:msg preferredStyle:UIAlertControllerStyleAlert];



                    [alertCtrl addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Yes",@"Generic confirm") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                        // do your stuff

                        // very important to hide the window afterwards.


                        window.hidden = YES;

                    }]];

                    UIAlertAction *cancelAction= [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                         window.hidden = YES; 

                    }];

                    [alertCtrl addAction:cancelAction];

                    //http://stackoverflow.com/questions/25260290/makekeywindow-vs-makekeyandvisible

                    [window makeKeyAndVisible]; //The makeKeyAndVisible message makes a window key, and moves it to be in front of any other windows on its level

                    [window.rootViewController presentViewController:alertCtrl animated:YES completion:nil];

                });
Utsav Dusad
  • 2,139
  • 4
  • 31
  • 52
0

Use below code to present UIAlertController from NSObject class.

[[[UIApplication sharedApplication] delegate].window.rootViewController presentViewController:alertViewController animated:true completion:nil];
Bhavesh Patel
  • 596
  • 4
  • 17