Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform background tasks when app is terminated

Tags:

ios

swift

I'm creating an application for my school which should check every n minutes if there is a new mark on the website. To do this when the user login for the first time, the number of the actual mark is saved in the "UserDefaults". When app is terminated, after n minutes, the number of mark is recounted and compared with the previous one and send a notification in case the number is changed.

What I'd like to know if there is a way to perform this task. I've tried to create a timer in -applicationWillTerminate- but it's fired only once. This is what I tried:

func applicationWillTerminate(_ application: UIApplication) {
    DispatchQueue.main.async {
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AppDelegate.findMark), userInfo: nil, repeats: true)
        self.timer.fire()
    }
}

Selector findMark is the task.

Thanks in advance!

like image 746
Sellone Ciompi Avatar asked Nov 06 '16 13:11

Sellone Ciompi


People also ask

Does background fetch work when app is terminated?

The Background Fetching will NOT happen in your app after the user has killed it in the multitasking UI. This is by design.

Will iOS terminate the app running in background after a specific time?

At the same time, didReceiveMemoryWarning is invoked for the app. At this point, so that your app continues to run properly, the OS begins terminating apps in the background to free some memory. Once all background apps are terminated, if your app still needs more memory, the OS terminates your app.

What are background tasks iPhone?

Overview. Use the BackgroundTasks framework to keep your app content up to date and run tasks requiring minutes to complete while your app is in the background. Longer tasks can optionally require a powered device and network connectivity.


1 Answers

You have two options

  1. Background App Refresh
  2. Silent push notifications

Easiest one is Background App Refresh. Because later one needs a server to send the notification. You can check following API for the usage. Basically you set Background Fetch capability on Capabilities/Background Modes of your app. Then from time to time, iOS will wake up your app and call application(_:performFetchWithCompletionHandler:) delegate. You will have around 30-45 seconds to call your function and call completion handler. If you don't finish it on time, iOS will kill your app. If you don't obey the rules, iOS will give you less chances to wake up. For more detailed usage of Background Modes, you may check following tutorial

like image 192
Meanteacher Avatar answered Oct 19 '22 06:10

Meanteacher