ioslifecyclebackground-fetch

what is the use of performFetchWithCompletionHandler in app delegate?


I am a bit confused with how performFetchWithcompletionHandler engaged with the iOS app life cycle. In the docs it's mentioned that it gives us 30 seconds to download any data but will our app freeze for 30 seconds at that time?


Solution

  • ... will our app freeze for 30 seconds at that time?

    No, the exact opposite. This method is called when your app is suspended, but the OS is going to let you check for data to retrieve. So, your app will be awaken, run in background, and this method will be called, at which point you can perform your quick fetch (not more than 30 seconds) to see if there is any data to retrieve. When you’re done processing your quick fetch, you call the completion handler to let the OS know that you’re done and that your app can safely be suspended again.

    If, though, you fail to complete your request in 30 seconds, your app may be summarily terminated and not participate in future background fetches. So it’s important to finish in the allotted time.


    As the docs say:

    Implement this method if your app supports the fetch background mode. When an opportunity arises to download data, the system calls this method to give your app a chance to download any data it needs. Your implementation of this method should download the data, prepare that data for use, and call the block in the completionHandler parameter.

    When this method is called, your app has up to 30 seconds of wall-clock time to perform the download operation and call the specified completion handler block. In practice, your app should call the completion handler block as soon as possible after downloading the needed data. If you do not call the completion handler in time, your app is terminated. More importantly, the system uses the elapsed time to calculate power usage and data costs for your app’s background downloads. If your app takes a long time to call the completion handler, it may be given fewer future opportunities to fetch data in the future. For more information about supporting background fetch operations, see Background Execution in App Programming Guide for iOS.