Search code examples
iosbatterysavestate

iOS Save State when device turns off or battery drains


I have an app that syncs records created on the phone with a web-server.

When app does not have internet connectivity, it store everything locally (Core Data) and then syncs it when internet is available again.

Now a user has come up with a valid user case scenario ... say he is in an airplane making records (without network) ... so everything is getting stored locally. All is well till the air hostess commands him to switch off the phone. While in the app he immediately turns if off. Now the data is getting lost. I am saving sate while app goes in background or even when phone is locked. But how do I warrant for this?

When user switches off the phone (long-pressing lock button), they still have to slide a bar and devices takes some time before switching off ... so there is some time I can save state in ... which delegate method is called during this time?


Solution

  • Your app will get applicationWillResignActive, applicationDidEnterBackground, applicationWillTerminate calls, in that order.

    http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW3

    You can use applicationWillTerminate as a cue to save stuff.

    However it is standard good practice to make sure your data is saved periodically as you go along and not just in these situations - what about if your user has entered lots of lots and data and then your app crashes, the data will be lost.

    I'm not very familiar with Core Data but surely it must have atomic save ability.