Lê Khánh Vinh Lê Khánh Vinh - 2 months ago 9
iOS Question

"Application tried to present a nil modal view controller on target" Error on iOS7 and below

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

(a 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 below. From version 8 and above nothing wrong. How to fix this? Any help is much appreciate. Thanks!


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];