Zhang Zhan
Zhang Zhan

Reputation: 905

Call a method when iOS is crashing

I have an iOS app that keeps checking the data, and I have implemented method for AppWillTerminate It works fine when the app is closed by user, the data is saved before the app is closed.

However, sometimes when the app is running at the background and user switch to other iOS app, and while they are using other apps, iOS could crash.

When I say iOS crashes, I mean it goes to black screen and restart again.

And in this scenario, my app's "willTerminate" is not called, therefore, my app's data is lost.

My question is, is there a way to save my app's data before iOS crashing?

Upvotes: 0

Views: 2132

Answers (3)

Vishal Adatia
Vishal Adatia

Reputation: 94

Try this :

In AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSSetUncaughtExceptionHandler(&HandleException);

    struct sigaction signalAction;
    memset(&signalAction, 0, sizeof(signalAction));
    signalAction.sa_handler = &HandleSignal;

    sigaction(SIGABRT, &signalAction, NULL);
    sigaction(SIGILL, &signalAction, NULL);
    sigaction(SIGBUS, &signalAction, NULL);
}

void HandleException(NSException *exception) {
/** NSLog(@"App crashing with exception: %@", [exception callStackSymbols]); */
/* Save somewhere that your app has crashed. */
}

void HandleSignal(int signal) {
/**NSLog(@"We received a signal: %d", signal); */
/** Save somewhere that your app has crashed. */
}

Upvotes: 1

Qazi
Qazi

Reputation: 381

As mentioned in the comments (I cant comment at the moment otherwise would have mentioned it there) the best way is to save the data in your applicationDidEnterBackground: function in AppDelegate. As per apple when your app is in background it is in suspended state which means Apple can terminate it whenever it wants without notifying the app if the active app (the one running on foreground needs more resources). So your app goes from Suspended state (the state where it was put when it was sent to background) to Terminated while other apps were used, and when it becomes active again it starts from scratch, so actually its not crashing (wont raise an exception) but just being restarted if it was terminated while being in the back ground.

this is a nice read in understanding the, App Lifecycle

Upvotes: 0

Sudeep
Sudeep

Reputation: 806

Try this.

In your application: didFinishLaunchingWithOptions: method, add this.

NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);

And add the following to your AppDelegate.

void uncaughtExceptionHandler () {
    // method to save data
}

Upvotes: 1

Related Questions