Update Live Activity once per second - Swift

3.3k views Asked by At

I'm searching for a way to update the Live Activity every second or every 2 seconds without using Push Notifications while keeping the app in background.

Do you have any suggestions? I tried something like this, but after few seconds it's stop working:

       var bgTask = UIBackgroundTaskIdentifier(rawValue: 1324)
        bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
            UIApplication.shared.endBackgroundTask(bgTask)
        })
        let timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(updateInfo), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: .default)
3

There are 3 answers

6
Morniak On

As mentioned in the documentation, "The delay between the time you schedule a background task and when the system launches your app to run the task can be many hours".

Unfortunately, background tasks are not suitable for your needs. Using Push notifications is the only way (that I know of at least) to achieve what you are trying to do.

0
marcinax On

It seems like there is no way to update the Live Activity every single second or in any other too frequent manner. Looks like battery saving is crucial here and system cuts off the updates after a few seconds, even if the application is running in the background.

If you need to display a timer on the LiveActivity, according to the docs, it's possible to use the following initializer of Text which seems to be dedicated for that use case:

init(timerInterval: ClosedRange<Date>, pauseTime: Date? = nil, countsDown: Bool = true, showsHours: Bool = true)

For example:

Text(timerInterval: context.state.deliveryTimer, countsDown: true)

It creates an instance that displays a timer counting within the provided interval. It just counts time automatically so it's not necessary to think about implementing timer on your own. However, there is no way of listening when timer ends to update the activity so looks like it might be necessary to schedule a notification or background task anyway and receive/run and handle it when timer ends.

Seems like apps mentioned here use a mechanism I described above. You have to consider your use case and decide whether Live Activities are suitable for your app.

0
iSpain17 On

You should carefully read the Discussion part of the beginBackgroundTask method:

The most important information in that secrion is that if you begin the task too late (like termination handler, didEnterBackground, etc.) it might not get registered appropriately.

My app updates the live activity even faster than once-per-second, it performs image processing in the background and it works. I start the background task as early as the work scheduled by the user begins, not before the app would enter background. Background tasks should be created pro-actively, not retro-actively.