0

I need to execute a task when the app is in background state. For example, when the app enters the background state, then every 5 minutes(app is in background in this time) a task is executed. I tried with location changed but I can't use a precise location(for battery consume) then I used significant location changed but If user doesn't move or doesn't change cell tower location is not updated.

Can you help me about it?

Peter Hornsby
  • 4,208
  • 1
  • 25
  • 44
alexander
  • 149
  • 1
  • 2
  • 14
  • This depends on what you are wanting to do in the background. iOS only allows for specific tasks to occur in the background: [Implementing Long-Running Tasks](https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW4) – Wayne Ellery Nov 01 '16 at 22:40
  • 1
    You probably need to re-think your approach. iOS doesn't let suspended applications schedule execution for specific time intervals. What is the nature of the task? Perhaps you can trigger it some other way, such as a server push – Paulw11 Nov 01 '16 at 22:46
  • Read this: https://blog.newrelic.com/2016/01/13/ios9-background-execution/ – Tarvo Mäesepp Nov 01 '16 at 23:24

1 Answers1

0

Yo could use the iOS Background Fetch feature where you can specify minimum background fetch interval. But actual interval between successive invocation of your code will be determined by iOS framework.

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

    let data: String? = nil

    do {
        //fetch some data
        if let data = getSomeNewData() {
            /* use the completionHandler to talk to the system and tell us if the app fetched new data, or if no data was available. */
            completionHandler(.newData)
        } else {
            completionHandler(.noData)
        }
    }  catch {
        print(error)
        completionHandler(.failed)
    }

}

see also question: swift-ios-refreshing-app-data-when-in-background

Another option is to setup a server that will send a (silent) push notification to your app every 5 minutes that your app can react to.

Community
  • 1
  • 1
kiatra
  • 151
  • 10