How to execute code when my application is completed in background in ios

In iOS, we all know that there is an AppDelegate applicationWillTerminate method, and it is called when my application is closed by the user, when it is running (that is, not in the background). But I want to do something (for example, save data) when my application is completed (closed by the user or killed by the OS), when it runs in the background.

PS: my application can run in the background.

Do you have any solutions? thanks.

+6
source share
2 answers

Sorry, but you should use applicationWillTerminate :

This method allows your application to know that it must be completed and completely erased from memory. You should use this method to complete any final cleanup tasks for your application, such as freeing up shared resources, saving user data, and canceling timers. Your implementation of this method takes about five seconds to complete any tasks and return. If the method does not return before the time runs out, the system can kill the whole process.

For applications that do not support background execution or are connected in iOS 3.x or earlier, this method is always called when the user exits the application. For applications that support background execution, this method is usually not called when the user exits the application, because the application in this case simply moves to the background. However, this method can be called in situations when the application is running in the background (not paused), and the system must terminate it for some reason.

Therefore, if you need to save the data ALSO when the user manually kills the application, use applicationDidEnterBackground , which it caused if your application supports background mode.

+7
source

If you need to execute the code when your application does not work, there are several options available for you depending on what you are trying to do.

  1. Background fetching will allow your application to run in the background for about 30 seconds at the scheduled interval. The goal of this is to get the data and prepare your user interface for the next application launch.
  2. Push notifications allow your application to receive fresh data from your server. You can make a message appear on the device if you want, but this is not necessary - quiet push notifications allow you to skip this part.
  3. Local notifications allow you to display a warning for the user, as well as any media attachments you want, and some options for the user to choose from. If they choose these options, then your application can be launched in the foreground or in the background to deal with 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: fooobar.com/questions/1001314 / ...

+1
source

All Articles