Looking at background fetch in more depth

Now that you have a broad understanding of background fetch, let's investigate what your app needs to do in order to be compatible with background fetch. First of all, you will need to let iOS know that your app wants to be woken up periodically. To do this, you will need to turn on the Background Modes capability for your app. Within this capability, you can opt into for background fetch. Enabling this mode will automatically add a key for this service to your app's Info.plist.

When this capability is enabled, iOS will allow your app to be woken up periodically. However, it won't magically work right away. In the AppDelegate's application(_:didFinishLaunchingWithOptions:) method, we must inform the system that we actually want our app to become active every once in a while and also specify the interval we desire.

Then, once this is done, your application will be awoken in the background, and the application(_:performFetchWithCompletionHandler:) method is called whenever we're allowed to do work. This method should be implemented in AppDelegate, and it's expected to call the provided completion handler once the work is completed. If you fail to call this method in time, iOS will make a note of this, and missing the window to call this completion handler could result in your app not being woken up as often as you'd like.

Once the completion handler is called, your app will be put back to sleep until the user opens the app or until the next time your app is allowed to perform a background fetch. Calling the completion handler shouldn't be done until all of the work that you intended to do is done because once the completion handler is called, there are no guarantees about how and when your app will make a transition to the background, except that it will happen soon.