how to execute code when my app terminated in background in ios

If you need to execute code when your app isn’t running, there are several options open to you depending on what you’re trying to do.

  1. Background fetch will let your app run in the background for about 30 seconds at scheduled intervals. The goal of this is to fetch data and prepare your UI for when the app runs next.
  2. Push notifications let your app fetch fresh data from your server. You can make a message appear on the device if you want, but it’s not required – silent push notifications let you skip that part.
  3. Local notifications let you display an alert to the user, along with any media attachments you want and some options for the user to select from. If they choose those options then your app can be launched in the foreground or background to handle them.

From: https://www.hackingwithswift.com/example-code/system/how-to-run-code-when-your-app-is-terminated

You can also use Silent Push Notification as I mentioned in a similar question: https://stackoverflow.com/a/57245980/6157415


Sorry but you should use applicationWillTerminate:

This method lets your app know that it is about to be terminated and purged from memory entirely. You should use this method to perform any final clean-up tasks for your app, such as freeing shared resources, saving user data, and invalidating timers. Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.

For apps that do not support background execution or are linked against iOS 3.x or earlier, this method is always called when the user quits the app. For apps that support background execution, this method is generally not called when the user quits the app because the app simply moves to the background in that case. However, this method may be called in situations where the app is running in the background (not suspended) and the system needs to terminate it for some reason.

So if you need to save data ALSO when user manually kill the app use applicationDidEnterBackground that it's called if your app support background mode.

Tags:

Ios

Background