Search code examples
iosswiftiphonexcode

BGAppRefreshTask in the BackgroundTasks


I have this code that show a message "Msg Background" when the application is in Background. What I need is that as long as the application continues in the background show that message every 2 minutes (just an example of time). So far the code I have shows the message only once, apparently this sentence is not working properly.

UIApplication.shared.setMinimumBackgroundFetchInterval (UIApplication.backgroundFetchIntervalMinimum)

I also have this warning: 'setMinimumBackgroundFetchInterval' was deprecated in iOS 13.0: Use a BGAppRefreshTask in the BackgroundTasks framework instead

I am using swift 5 and Xcode 11

class AppDelegate: UIResponder, UIApplicationDelegate {



func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    GMSServices.provideAPIKey("AIzaSyBSpAt5zqvbh73FmG_Kb6xpiFMkWRmHppg")
    UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
    return true
}

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("Msg Background")
}

}

Solution

  • As Paulw11 said, it's not called in fixed interval. The OS controls when it is going to be executed. We cannot expect the specific time because of it.

    You probably know this, but I'm going to add this bit just in case, setMinimumBackgroundFetchInterval has deprecated on iOS 13 and later. You might want to consider to use BackgroundTasks Framework instead.

    but if you want to test performFetchWithCompletionHandler, you can use XCode Navigation Bar > Debug > perform Background Fetch.

    Screenshot of XCode navigation bar to find option:

    enter image description here

    I hope it can help!