Search code examples
iosswiftuploadsaveusage-statistics

Save app data before app quits iOS


I have an App written in Swift that uploads statistics to my server. My question is simple and as follows: When is the best time to upload my statistics?

One approach I came up with was that I save all the statistics locally when the app quits. And when the app opens in the future, I upload the saved statistics and clear them.

The problem is applicationWillTerminate is not called sometimes, and data may be lost without being uploaded.

So what is the best way to solve my problem?

Thanks.


Solution

  • Save your data locally whenever its generated. Once the app launches, send it and clear your local cache. You can use application:didFinishLaunchingWithOptions: to detect launching.

    Its a good practice to cache information that you need to keep safe periodically, instead of all at once.