How to execute code inside performFetchWithCompletionHandler only when application is in active state?

I want to perform some action during some interval of time.But this should not occour when app is in background or inactive state. I have implemented this as follows

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
   return true
}

And in the performFetchWithCompletionHandler

 func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    print("Background fetch called")



        // foreground

    if (application.applicationState == .active)
    {

        //lines of code to perform



}
}

But when I tried simulating background fetch in simulator ,it is showing the following message

Warning: Application delegate received call to -application:performFetchWithCompletionHandler: but the completion handler was never called.

I tried removing the application state condition and it is working fine.But i want to perform these lines only when app is active and not in background or inactive state.How can I achieve this?

Upvotes: 0

Views: 211

Answers (1)

glyvox
glyvox

Reputation: 58099

You forgot to add the completion handler to the function. It should be called when the data fetch completed.

Insert this to your code if you have new data to display:

completionHandler(.newData)

...this if you have no data:

completionHandler(.noData)

...and this if the fetch failed:

completionHandler(.failed)

Upvotes: 1

Related Questions