12

I need to save some data in my application, when the application terminates and even if it crashes. I know that applicationWillTerminate is called when application terminates but I am not sure which method is called when application crashes.
Can someone help me here?

James Webster
  • 31,873
  • 11
  • 70
  • 114
Nitish
  • 13,845
  • 28
  • 135
  • 263
  • 1
    you should write an app that doesn't crash, which solves your problem –  Feb 13 '12 at 10:22
  • 2
    Very good consideration Vince. But you never know what might crash your application. Dealing with it earlier is better than doing it later on. – Nitish Feb 13 '12 at 10:28

2 Answers2

16

Well you could add your own exception handler, to catch the error.

First you need to define the exception method:

void uncaughtExceptionHandler(NSException *exception) {
    // You code here, you app will already be unload so you can only see what went wrong.
}

Then tell the app to use your exception handler:

- (void)applicationDidFinishLaunching:(UIApplication *)application { 
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    // The rest if you code  ....
}

There is no way to make the app save data on crashing, since saving could be the reason for the crash!

rckoenes
  • 69,092
  • 8
  • 134
  • 166
  • Can I save current time (app crash time) in NSUserDefaults in this uncaughtExceptionHandler method? Is it best practice? – Bhushan B Jan 28 '16 at 09:57
  • I don't think you can, but you can write your error to the applications sandbox, This is how libraries like crashlytics, hockyapp and sorts work. – rckoenes Jan 28 '16 at 10:02
  • thanks for quick response. Is there another way to save current time when app crash? I am saving time in applicationWillTerminate method but it's not calling when app crashes. Actually my application is in a way that I need last session logout time to process further. Any help you can provide would be appreciated. – Bhushan B Jan 28 '16 at 10:33
  • Well if the user kills the app, by swiping up in the task switcher, you will not be able to run any code. Since this will just drop you app from memory directly. From a crash you can use the my example above and just write the `NSDate` to the file system. – rckoenes Jan 28 '16 at 10:55
-5

No, you cannot get to know when the application crashes.

Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55