Repository navigation
fix: [SDK-5580] end duplicate Live Activities and keep the update token #1780
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| /* | ||
| Modified MIT License | ||
|
|
||
| Copyright 2026 OneSignal | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| 1. The above copyright notice and this permission notice shall be included in | ||
| all copies or substantial portions of the Software. | ||
|
|
||
| 2. All copies of substantial portions of the Software may only be used in connection | ||
| with services provided by OneSignal. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| THE SOFTWARE. | ||
| */ | ||
|
|
||
| // Effectively blanks out this file for Mac Catalyst | ||
| #if targetEnvironment(macCatalyst) | ||
| #else | ||
| import OneSignalCore | ||
| import ActivityKit | ||
|
|
||
| /// Tests cannot create an `Activity`, so the helpers below take this protocol. | ||
| protocol OSLiveActivityInstance { | ||
| var id: String { get } | ||
| var oneSignalActivityId: String { get } | ||
| var pushTokenString: String? { get } | ||
| var isLive: Bool { get } | ||
| } | ||
|
|
||
| @available(iOS 16.1, *) | ||
| extension Activity: OSLiveActivityInstance where Attributes: OneSignalLiveActivityAttributes { | ||
| var oneSignalActivityId: String { attributes.onesignal.activityId } | ||
| var pushTokenString: String? { pushToken?.map { String(format: "%02x", $0) }.joined() } | ||
| var isLive: Bool { activityState != .ended && activityState != .dismissed } | ||
| } | ||
|
|
||
| extension OneSignalLiveActivitiesManagerImpl { | ||
| static func duplicateGroups<T: OSLiveActivityInstance>(_ activities: [T]) -> [String: [T]] { | ||
| Dictionary(grouping: activities.filter { $0.isLive }, by: { $0.oneSignalActivityId }).filter { $0.value.count > 1 } | ||
| } | ||
|
|
||
| /// The backend sends updates to the cached update token, so we prefer the | ||
| /// activity that has that token. | ||
| static func activityToKeep<T: OSLiveActivityInstance>(_ group: [T], cachedUpdateToken: String?) -> T? { | ||
| group.first { $0.pushTokenString != nil && $0.pushTokenString == cachedUpdateToken } | ||
| ?? group.first { $0.pushTokenString != nil } | ||
| ?? group.first | ||
| } | ||
|
|
||
| static func endDuplicates<T: OSLiveActivityInstance>( | ||
| _ groups: [String: [T]], | ||
| cachedUpdateToken: (String) async -> String?, | ||
| end: (T) async -> Void | ||
| ) async -> [T] { | ||
| var kept = [T]() | ||
| // An activity can end during any await below, so we read isLive again | ||
| // before we keep or end an activity. | ||
| for (activityId, group) in groups { | ||
| let cachedToken = await cachedUpdateToken(activityId) | ||
| guard let keeper = activityToKeep(group.filter { $0.isLive }, cachedUpdateToken: cachedToken) else { | ||
| continue | ||
| } | ||
| kept.append(keeper) | ||
| for duplicate in group where duplicate.id != keeper.id && duplicate.isLive { | ||
| await end(duplicate) | ||
| } | ||
| } | ||
| return kept.filter { $0.isLive } | ||
| } | ||
|
|
||
| @available(iOS 16.2, *) | ||
| static func endDuplicateActivities<Attributes: OneSignalLiveActivityAttributes>( | ||
| _ groups: [String: [Activity<Attributes>]], | ||
| cachedUpdateToken: (String) async -> String? | ||
| ) async -> [Activity<Attributes>] { | ||
| await endDuplicates(groups, cachedUpdateToken: cachedUpdateToken) { duplicate in | ||
| OneSignalLog.onesignalLog(.LL_DEBUG, message: "OneSignal.LiveActivities ending duplicate activity: \(Attributes.self):\(duplicate.oneSignalActivityId):\(duplicate.id)") | ||
| await duplicate.end(nil, dismissalPolicy: ActivityUIDismissalPolicy.immediate) | ||
| } | ||
| } | ||
|
|
||
| static func hasLiveDuplicate<T: OSLiveActivityInstance>(_ activity: T, in activities: [T]) -> Bool { | ||
| activities.contains { $0.id != activity.id && $0.oneSignalActivityId == activity.oneSignalActivityId && $0.isLive } | ||
| } | ||
| } | ||
| #endif | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -38,7 +38,7 @@ | |
|
|
||
| @objc(OneSignalLiveActivitiesManagerImpl) | ||
| public class OneSignalLiveActivitiesManagerImpl: NSObject, OSLiveActivities { | ||
| private static let _executor: OSLiveActivitiesExecutor = OSLiveActivitiesExecutor(requestDispatch: DispatchQueue(label: "OneSignal.LiveActivities")) | ||
|
|
||
| @objc | ||
| public static func liveActivities() -> AnyClass { | ||
|
|
@@ -65,7 +65,7 @@ | |
| @objc | ||
| @available(iOS 17.2, *) | ||
| public static func setPushToStartToken(_ activityType: String, withToken: String) throws { | ||
| OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities setStartToken called with activityType: \(activityType) token: \(withToken)") | ||
|
|
||
| guard let activityType = activityType.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlUserAllowed) else { | ||
| throw LiveActivitiesError.invalidActivityType("Cannot translate activity type to url encoded string.") | ||
|
|
@@ -220,13 +220,13 @@ | |
| - clickId: UUID representing the unique click event, as it is possible for this click to be tracked multiple times. | ||
| */ | ||
| private static func trackClick(clickId: String, activityType: String, activityId: String, notificationId: String?) { | ||
| OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities trackClick called with clickId: \(clickId), activityType: \(activityType), activityId: \(activityId)") | ||
| let req = OSRequestLiveActivityClicked(key: clickId, activityType: activityType, activityId: activityId, notificationId: notificationId) | ||
| _executor.append(req) | ||
| } | ||
|
|
||
| @available(iOS 17.2, *) | ||
| private static func listenForPushToStart<Attributes: OneSignalLiveActivityAttributes>(_ activityType: Attributes.Type, options: LiveActivitySetupOptions? = nil) { | ||
| if options == nil || options!.enablePushToStart { | ||
| Task { | ||
| OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OneSignal.LiveActivities listening for pushToStart on: \(activityType)") | ||
|
|
@@ -239,7 +239,7 @@ | |
| } | ||
|
|
||
| @available(iOS 16.1, *) | ||
| private static func listenForActivity<Attributes: OneSignalLiveActivityAttributes>(_ activityType: Attributes.Type, options: LiveActivitySetupOptions? = nil) { | ||
|
|
||
| /* | ||
| Apple has confirmed that when using push-to-start, it is best to check both `Activity<...>.activities` in addition | ||
|
|
@@ -249,11 +249,22 @@ | |
| */ | ||
|
|
||
| // Establish listeners for activity (if any exist) | ||
| for activity in Activity<Attributes>.activities { | ||
| listenForActivityStateUpdates(activityType, activity: activity, options: options) | ||
| listenForActivityPushToUpdate(activityType, activity: activity, options: options) | ||
| if #available(iOS 16.2, *) { | ||
| listenForContentUpdates(activityType, activity: activity) | ||
| let activities = Activity<Attributes>.activities | ||
| var duplicates = [String: [Activity<Attributes>]]() | ||
| if #available(iOS 16.2, *) { | ||
| duplicates = duplicateGroups(activities) | ||
| } | ||
| // If a duplicate that we end gets listeners, its token replaces the | ||
| // kept activity's token. | ||
| for activity in activities where duplicates[activity.oneSignalActivityId] == nil { | ||
| listenForActivityEvents(activityType, activity: activity, options: options) | ||
| } | ||
|
|
||
| if #available(iOS 16.2, *), !duplicates.isEmpty { | ||
| Task { | ||
| for activity in await endDuplicateActivities(duplicates, cachedUpdateToken: _executor.cachedUpdateToken) { | ||
| listenForActivityEvents(activityType, activity: activity, options: options) | ||
| } | ||
| } | ||
|
Comment on lines
+263
to
268
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Act on (3/3): This cleanup runs concurrently with the Those rules disagree (cached token vs newest). On push-to-start the same activity can appear in both Serialize both paths through one keeper policy, and skip |
||
| } | ||
|
|
||
|
|
@@ -265,22 +276,27 @@ | |
| // if there's already an activity with the same OneSignal activityId, dismiss it before | ||
| // listening for the new activity's events. | ||
| for otherActivity in Activity<Attributes>.activities { | ||
| if activity.id != otherActivity.id && otherActivity.attributes.onesignal.activityId == activity.attributes.onesignal.activityId { | ||
| OneSignalLog.onesignalLog(.LL_DEBUG, message: "OneSignal.LiveActivities dismissing other activity: \(activityType):\(otherActivity.attributes.onesignal.activityId):\(otherActivity.id)") | ||
| await otherActivity.end(nil, dismissalPolicy: ActivityUIDismissalPolicy.immediate) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| listenForActivityStateUpdates(activityType, activity: activity, options: options) | ||
| listenForActivityPushToUpdate(activityType, activity: activity, options: options) | ||
| if #available(iOS 16.2, *) { | ||
| listenForContentUpdates(activityType, activity: activity) | ||
| } | ||
| listenForActivityEvents(activityType, activity: activity, options: options) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @available(iOS 16.1, *) | ||
| private static func listenForActivityEvents<Attributes: OneSignalLiveActivityAttributes>(_ activityType: Attributes.Type, activity: Activity<Attributes>, options: LiveActivitySetupOptions? = nil) { | ||
| listenForActivityStateUpdates(activityType, activity: activity, options: options) | ||
| listenForActivityPushToUpdate(activityType, activity: activity, options: options) | ||
| if #available(iOS 16.2, *) { | ||
| listenForContentUpdates(activityType, activity: activity) | ||
| } | ||
| } | ||
|
|
||
| @available(iOS 16.1, *) | ||
| private static func listenForActivityStateUpdates<Attributes: OneSignalLiveActivityAttributes>(_ activityType: Attributes.Type, activity: Activity<Attributes>, options: LiveActivitySetupOptions? = nil) { | ||
| // listen for activity dismisses so we can forget about the token | ||
|
|
@@ -289,7 +305,12 @@ | |
| for await activityState in activity.activityStateUpdates { | ||
| switch activityState { | ||
| case .dismissed: | ||
| OneSignalLiveActivitiesManagerImpl.exit(activity.attributes.onesignal.activityId) | ||
| // If a live duplicate exists, `exit` can stop its updates. | ||
| if hasLiveDuplicate(activity, in: Activity<Attributes>.activities) { | ||
| OneSignalLog.onesignalLog(.LL_DEBUG, message: "OneSignal.LiveActivities keeping update token for: \(activityType):\(activity.attributes.onesignal.activityId):\(activity.id), a duplicate is still live") | ||
| } else { | ||
| OneSignalLiveActivitiesManagerImpl.exit(activity.attributes.onesignal.activityId) | ||
| } | ||
| case .active: break | ||
| case .ended: break | ||
| case .stale: break | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Act on (3/3): The keeper is chosen once. If it dies during
await end(duplicate)(user dismiss, or theactivityUpdatespath), this loop still ends every remaining live sibling, thenkept.filter { $0.isLive }returns nothing.Listeners are attached only after this returns, and
activityStateUpdatesdoes not replay, soexitis never called. The update-token cache / backend can keep pushing to a dead token.testEndDuplicates_whenTheKeeperEndsDuringTheAwaits_returnsNothingcurrently encodes this.Re-check
keeper.isLiveafter each await, promote a new keeper if needed, andexit(activityId)if nothing is still live.