1

App crash when click on push notification but when app is only in kill state.In background working fine.

Fatal Exception: NSInternalInconsistencyException Application windows are expected to have a root view controller at the end of application launch

 Fatal Exception: NSInternalInconsistencyException
    0  CoreFoundation                 0x183be3164 __exceptionPreprocess
    1  libobjc.A.dylib                0x182e2c528 objc_exception_throw
    2  CoreFoundation                 0x183be3038 +[NSException raise:format:]
    3  Foundation                     0x18457d7f4 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:]
    4  UIKit                          0x18d402ec0 -[UIApplication _runWithMainScene:transitionContext:completion:]
    5  UIKit                          0x18d69e2a8 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke
    6  UIKit                          0x18d976100 +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:]
    7  UIKit                          0x18d69df0c -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]
    8  UIKit                          0x18d69e76c -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:]
    9  UIKit                          0x18de237c0 __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke
    10 UIKit                          0x18de23664 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]
    11 UIKit                          0x18db912cc __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke
    12 UIKit                          0x18dd2a3cc _performActionsWithDelayForTransitionContext
    13 UIKit                          0x18db9117c -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]
    14 UIKit                          0x18d975760 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:]
    15 UIKit                          0x18d401158 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:]
    16 UIKit                          0x18d816dbc -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:]
    17 FrontBoardServices             0x1862a61f0 -[FBSSceneImpl _didCreateWithTransitionContext:completion:]
    18 FrontBoardServices             0x1862aeaf8 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2
    19 libdispatch.dylib              0x183562a14 _dispatch_client_callout
    20 libdispatch.dylib              0x18356a200 _dispatch_block_invoke_direct$VARIANT$mp
    21 FrontBoardServices             0x1862da7f8 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__
    22 FrontBoardServices             0x1862da49c -[FBSSerialQueue _performNext]
    23 FrontBoardServices             0x1862daa38 -[FBSSerialQueue _performNextFromRunLoopSource]
    24 CoreFoundation                 0x183b8b77c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
    25 CoreFoundation                 0x183b8b6fc __CFRunLoopDoSource0
    26 CoreFoundation                 0x183b8af84 __CFRunLoopDoSources0
    27 CoreFoundation                 0x183b88b5c __CFRunLoopRun
    28 CoreFoundation                 0x183aa8c58 CFRunLoopRunSpecific
    29 GraphicsServices               0x185954f84 GSEventRunModal
    30 UIKit                          0x18d2015c4 UIApplicationMain
    31 EmergencMe                     0x10143dfac main (main.m:17)
    32 libdyld.dylib                  0x1835c856c start

Here is my code which run when app launch. But don't know where is bug:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              if (!error) {
                                  NSLog(@"request authorization succeeded!");
                                  //[self showAlert];
                              }
                          }];




// Branch Intigration
    Branch *branch = [Branch getInstance];

//    if is debug
//    [[Branch getInstance] setDebug];

    DecisionController * mainVC = [[DecisionController alloc] init];
    [mainVC viewDidLoad];
    [branch initSessionWithLaunchOptions:launchOptions andRegisterDeepLinkHandler:^(NSDictionary *params, NSError *error) {
        if (!error && params) {

            // params are the deep linked params associated with the link that the user clicked -> was re-directed to this app
            // params will be empty if no data found
            // ... insert custom logic here ...
            NSString * non_branch_link  = [params objectForKey:@"+clicked_branch_link"];
            if ([[params objectForKey:@"+clicked_branch_link"] boolValue]) {
                NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
                [nc postNotificationName:@"DeepLinkNotification" object:self userInfo:params];
            }
            NSLog(@"params: %@", params.description);
        }
    }];
//
//    // MAGICAL RECORD Intigration
    [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:@"EmergencMeDatabase.sqlite"];
//    [Fabric with:@[[branch class]]];
    NSLog(@"magical record path to SQLite base %@", [NSPersistentStore MR_defaultLocalStoreUrl]);
//    [Fabric with:@[[Crashlytics class]]];
    [[NSUserDefaults standardUserDefaults] setFloat:0 forKey:@"lastnotificationminute"];
    [[FBSDKApplicationDelegate sharedInstance] application:application
                             didFinishLaunchingWithOptions:launchOptions];
    [MPNotificationView registerNibNameOrClass:@"CustomNotificationView"
                        forNotificationsOfType:@"Custom"];
    [self registerForRemoteNotifications];
    [SharedRenderer sharedInstance].retryCount = 0;
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"generatenotification"];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"FirstSubscribe"];
    mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone"
                                               bundle: nil];
    if (launchOptions[UIApplicationLaunchOptionsLocationKey]) {

        [self startLocationManager:@""];
    }
    @try
    {
        //attempt to retrieve the dictionary
        if (![[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"])
        {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
            [SharedRenderer setValue:@"0" key:@"alldatafetched"];
            [SharedRenderer setValue:@"" key:@"currentchannel"];
            NSMutableArray* alerts = [[NSMutableArray alloc] init];
            NSData* alertsData=[NSKeyedArchiver archivedDataWithRootObject:alerts];
            [[NSUserDefaults standardUserDefaults] setObject:alertsData forKey:@"nonreasonalerts"];
            NSMutableArray* receivedAlerts = [[NSMutableArray alloc] init];
            NSData* receivedAlertsData=[NSKeyedArchiver archivedDataWithRootObject:receivedAlerts];
            [[NSUserDefaults standardUserDefaults] setObject:receivedAlertsData forKey:@"receivedalerts"];
            NSMutableArray* myAlerts = [[NSMutableArray alloc] init];
            NSData* myAlertsData=[NSKeyedArchiver archivedDataWithRootObject:myAlerts];
            [[NSUserDefaults standardUserDefaults] setObject:myAlertsData forKey:@"myalerts"];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"OB"];
            [[NSUserDefaults standardUserDefaults] synchronize];

        }
        if (![[SharedRenderer getValueFor:@"isLogin"] boolValue])
        {
            navigationController = [mainStoryboard instantiateViewControllerWithIdentifier:@"loginVC"];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"showhomealert"];
        }
        else
        {
            if ([[SharedRenderer getValueFor:@"family_id"] isEqualToString:@""] || [[SharedRenderer getValueFor:@"alldatafetched"] isEqualToString:@"0"])
            {
                navigationController = [mainStoryboard instantiateViewControllerWithIdentifier:@"Smarticestep1"];
            }
            else
            {
                navigationController = [mainStoryboard instantiateViewControllerWithIdentifier:@"homenav"];
                [self activatedeacAlertTimer];
                [self activatePendingAlertTimer];
                [self checkFor_AlertDeactivation];
                [self fetchInvitationCount];
                // Mark by Mian:
                //            [self updatePSAlertTable];
            }
        }

        navigationController = [mainStoryboard instantiateViewControllerWithIdentifier:@"loginVC"];
        [self.window setRootViewController: navigationController];

        [self.window setRootViewController: navigationController];
        [self.window makeKeyAndVisible];

        LeftMenuViewController *leftMenu = (LeftMenuViewController*)[mainStoryboard
                                                                     instantiateViewControllerWithIdentifier: @"LeftMenuViewController"];
        RightMenuViewController *rightMenu = (RightMenuViewController*)[mainStoryboard
                                                                        instantiateViewControllerWithIdentifier: @"RightMenuViewController"];
        [SlideNavigationController sharedInstance].rightMenu = rightMenu;
        [SlideNavigationController sharedInstance].leftMenu = leftMenu;
        [SlideNavigationController sharedInstance].menuRevealAnimationDuration = .4;

        // Creating a custom bar button for right menu
        UIButton *button  = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        [button setImage:[UIImage imageNamed:@"gear"] forState:UIControlStateNormal];
        [button addTarget:[SlideNavigationController sharedInstance] action:@selector(toggleRightMenu) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        [SlideNavigationController sharedInstance].rightBarButtonItem = rightBarButtonItem;
        [[NSNotificationCenter defaultCenter] addObserverForName:SlideNavigationControllerDidClose object:nil queue:nil usingBlock:^(NSNotification *note)
         {
             //         NSString *menu = note.userInfo[@"menu"];
         }];

        [[NSNotificationCenter defaultCenter] addObserverForName:SlideNavigationControllerDidOpen object:nil queue:nil usingBlock:^(NSNotification *note)
         {
             //         NSString *menu = note.userInfo[@"menu"];
         }];

        [[NSNotificationCenter defaultCenter] addObserverForName:SlideNavigationControllerDidReveal object:nil queue:nil usingBlock:^(NSNotification *note)
         {
             //         NSString *menu = note.userInfo[@"menu"];
         }];
        [self ConnectPusher];
        if ([[SharedRenderer getValueFor:@"isLogin"] boolValue]){
            [self checkFor_AlertDeactivation];
            [self removePastAlert];
            [self deactivateAlert];
            [self goOnline_Offline:@"1"];
        }
        [self showAlert:launchOptions];
    }
    @catch (NSException *e)
    {
        //something went wrong
        //populate the NSError object so it can be accessed
        NSLog(@"Catch");
    }
//    NSArray *windows = [[UIApplication sharedApplication] windows];
//    for(UIWindow *window in windows) {
//        NSLog(@"window: %@",window.description);
//        if(window.rootViewController == nil){
//            UIViewController* vc = [[UIViewController alloc]initWithNibName:nil bundle:nil];
//            self.window.rootViewController = vc;
//        }
//    }
    return YES;
}
Shahbaz Akram
  • 1,598
  • 3
  • 28
  • 45
  • Possible duplicate of ["Application windows are expected to have a root view controller at the end of application launch" error when running a project with Xcode 7, iOS 9](https://stackoverflow.com/questions/30884896/application-windows-are-expected-to-have-a-root-view-controller-at-the-end-of-a) – MAhipal Singh Feb 15 '18 at 08:36
  • I read above but not working in my case. Its crash on specific notification not each notification – Shahbaz Akram Feb 15 '18 at 09:53
  • then you need to confirm your payload type.. key and values. – MAhipal Singh Feb 15 '18 at 09:57
  • and can you add the piece of code from didLaunch method where this crash happen.. – MAhipal Singh Feb 15 '18 at 10:02
  • @Rivendell Please see my update question – Shahbaz Akram Feb 15 '18 at 10:06
  • is that crash happened only when you try to launch home screen through push Notification when app is quite. – MAhipal Singh Feb 15 '18 at 10:21
  • @Rivendell yes exactly – Shahbaz Akram Feb 21 '18 at 10:51
  • you said, Its crash on specific notification not each notification, that mean application is properly navigate to home screen on tapping notification in some specific notification and not lead any crash. right ? – MAhipal Singh Feb 21 '18 at 11:20
  • then you have to first verify the notifications payload, may be required keys are not included in payload which lead crash while launching through those notification. – MAhipal Singh Feb 21 '18 at 11:22

1 Answers1

0

Set root view controller in didFinishLaunchingWithOptions method of AppDelegate

[window setRootViewController:viewController];

or from storyboard:

enter image description here

Arnab
  • 4,216
  • 2
  • 28
  • 50