Search code examples
iosswifttimerbackgroundnotifications

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.


Solution

  • 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)