Lê Khánh Vinh Lê Khánh Vinh - 11 months ago 45
iOS Question

"Application tried to present a nil modal view controller on target" Error on IOS7 and bellow

Hi I'm migrating old IOS project I got this error from my new line of code from helper class

(network call)

UIAlertController *alert = [UIAlertController alertControllerWithTitle:NO_INTERNET_ERROR_TITLE message:TRACKED_ITEM_NOT_FOUND_ERROR preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:ok];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];

The error is

016-08-16 13:52:49.955 SingPost[967:60b] *** Terminating app due to
uncaught exception 'NSInvalidArgumentException', reason: 'Application
tried to present a nil modal view controller on target

The problem only occur on IOS 7 and bellow. From 8 and above nothing wrong. How to fix this? Any help is much appreciate. Thanks!

Answer Source

As per iOS version you should make use of UIAlertView and UIAlertController:

   alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Invalid Coupon."  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        UIAlertController *alertController = [UIAlertController    alertControllerWithTitle:@"Warning" message:@"Invalid Coupon." preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *okAction = [UIAlertAction
                                   actionWithTitle:NSLocalizedString(@"OK", @"OK action")
                                   handler:^(UIAlertAction *action)


        [alertController addAction:okAction];

        [self presentViewController:alertController animated:YES completion:nil];