What is the correct way to save NSUserDefaults when my app is terminated on iOS

后端 未结 4 918
不知归路
不知归路 2021-02-10 03:16

I need to save my NSUserDefault when my app is completely quit in iOS. not didenterbackground and foreground. Only when user kill my app w

4条回答
  •  遇见更好的自我
    2021-02-10 03:29

    The problem is that applicationWillTerminate is not getting called at all.

    Change your applicationDidEnterBackground as below and kill your application within 20 seconds. You can see applicationWillTerminate getting called & setting your iCloud value properly in NSUserDefaults

    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
    
        __block UIBackgroundTaskIdentifier identifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            if (identifier != UIBackgroundTaskInvalid) {
                [[UIApplication sharedApplication] endBackgroundTask:identifier];
                identifier = UIBackgroundTaskInvalid;
            }
        }];
    
        dispatch_async(dispatch_get_main_queue(), ^{
            for (int i=0; i < 20; i++) {
                NSLog(@"%d", i);
                sleep(1);
            }
            if (identifier != UIBackgroundTaskInvalid) {
                [[UIApplication sharedApplication] endBackgroundTask:identifier];
                identifier = UIBackgroundTaskInvalid;
            }
        });
    }
    

提交回复
热议问题