Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Timer in the background

I want in my iOS application to start a timer when the app is running in the background and when the app is closed. The timer must check every 30 minutes of there a new notifications. In the timer function they call every 30 minutes another function showNotification().

How do I do this timer and on which place must I call the timer when the app is not running/run in the background.

like image 616
Laurens V Avatar asked Jan 18 '16 08:01

Laurens V


People also ask

Can iOS app run in background?

iOS puts strict limits on background execution. Its default behaviour is to suspend your app shortly after the user has moved it to the background; this suspension prevents the process from running any code. There's no general-purpose mechanism for: Running code continuously in the background.

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

iOS places strict limits on how long a background task can run, and if the EndBackgroundTask call is not made within the allotted time, the application will be terminated. By keeping track of the remaining backgrounding time, and using expiration handlers when necessary, we can avoid iOS terminating the application.

Does NSTimer run in background?

Problem is, NSTimer requires an active run loop which is not always readily available on background queues. The main thread has an active run loop but this defeats the purpose of having our timer run in the background so its a definite no go. So, to get a dedicated background-queue-friendly timer, we use GCD.


1 Answers

It is impossible to do something when the application is not in the foreground, with 100% certainty. You can use background fetch to be woken up periodically, but you can not control when it happens.

While there are some technical workarounds, and potentially even some hacky solutions (playing silent audio in the background), it sounds to me like your problem can be solved without the use of timers and background fetch.

Simply implement remote notifications. When your iOS receives a notification for your app, it will wake the app up and let it process for a while. You can then control what notifications are shown to the user, and maybe load some data in the background.

In broad terms, you need to:

  • register for remote notifications when your app starts (typically in application:didFinishLaunching:)
  • when you receive a notification token, send it to the web server that will send you the notifications (this token can change, so be sure to keep sending it to your web server whenever you start the app)
  • when new content is available, your web server can use the token to send a payload to your application (your choice of language probably already has a library for this. E.g. if you use Ruby, there is Houston)
like image 59
Janis Kirsteins Avatar answered Oct 20 '22 21:10

Janis Kirsteins