staleDate in ActivityKit (iOS 16.2 / 16.4) seems to have no effect
Asked Answered
I

0

6

I have a Live Activity and need to update it frequently like every minute or every few minutes in a similar way that the Uber app updates its Live Activity to show you the progress of the ride. I am aware that push notifications are a general alternative, but I want to understand the local path first since the current docs (as of iOS 16.4 / Xcode 14.3) seem to suggest to me that using staleDate + background tasks is one recommended way by Apple to keep your activity updated even if the docs are not specific on the frequency / time intervals between updates.

First, I set up my Activity like this:

if ActivityAuthorizationInfo().areActivitiesEnabled {
            let state = MyAttributes.ContentState(info: info)
            let attributes = MyAttributes(name: "test")
            let content = ActivityContent(state: state, staleDate: Date(timeIntervalSinceNow: Self.activityUpdateTimeInterval)) // e.g. 60 seconds
            currentActivity = try Activity.request(attributes: attributes, content: content)
            observeActivityStateUpdates()
}

In a second function observeActivityStateUpdates I am trying to observe changes to the activityStateUpdates stream:

private func observeActivityStateUpdates() {
    Task { [weak self] in
        guard let activityStateUpdates = self?.currentActivity?.activityStateUpdates else { return }
        for await update in activityStateUpdates {
            print("LiveActivity: new state \(String(reflecting: update))")
            if update == .stale {
                Task { [weak self] in
                    await self?.updateActivityWithNewData()
                }
            }
        }
        print("LiveActivity: task observing activityStateUpdates has ended.")
    }
}

So my expectation is that I would get a .stale value here when iterating over the async sequence in activityStateUpdates. But for some reasons this never happens. I only get the first .active update and then there never is a .stale update within reasonable testing time on iOS 16.4.1. I also never get to the task observing activityStateUpdates has ended print statement so it's not like the sequence just ends prematurely after one .active.

Am I misunderstanding the way staleDate and activityStateUpdates are intended to be used here?

Incumber answered 17/4, 2023 at 15:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.