/
ActivityController.swift
236 lines (212 loc) · 9.35 KB
/
ActivityController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import Foundation
import ActivityKit
import os.activity
enum ActivityWidgetDismissalPolicy {
case `default`, immediate, after(_ date: Date)
}
final class ActivityController {
enum LiveActivityError: Error {
case liveActivitiesNotSupported
}
private struct CachedState {
let state: LiveActivityAttributes.ContentState
let staleDate: Date?
let alert: (title: String, body: String)?
}
static let shared = ActivityController()
private var currentActivity: Activity<LiveActivityAttributes>?
private var latestCachedState: CachedState?
func restoreLiveActivity() {
for activity in Activity<LiveActivityAttributes>.activities {
os_log(.debug, "!!!!! restoreLiveActivity,\nid:\(activity.id)\ncontent: \(activity.content)")
}
}
func startLiveActivity(
attributes: LiveActivityAttributes,
initialState: LiveActivityAttributes.ContentState,
staleDate: Date? = nil,
relevanceScore: Double = 0
) {
do {
// https://engineering.monstar-lab.com/en/post/2022/09/30/Live-Activities/
// 1. Check if device supports Live Activities and that they are enabled
guard ActivityAuthorizationInfo().areActivitiesEnabled else {
throw LiveActivityError.liveActivitiesNotSupported
}
// 2. Cancel running activities of type `Attributes`
let finalContent = ActivityContent(state: initialState, staleDate: nil)
for activity in Activity<LiveActivityAttributes>.activities {
Task { @MainActor in
await activity.end(finalContent, dismissalPolicy: .immediate)
os_log(.debug, "!!!!! activity.end,\nid:\(activity.id)\ncontent: \(activity.content)")
}
}
// pushType: .token, reports error: SessionCore.PermissionsError
// https://developer.apple.com/forums/thread/712223
let activity = try Activity.request(
attributes: attributes,
content: .init(state: initialState, staleDate: staleDate, relevanceScore: relevanceScore),
pushType: nil
)
os_log("%@", type: .debug, "!!!!! startLiveActivity\nattributes:\(attributes)\nstate: \(initialState)\nstaleDate:\(staleDate)\nalert:\(relevanceScore)")
self.currentActivity = activity
observeUpdates(activity: activity)
if let cached = latestCachedState {
self.latestCachedState = nil
Task { @MainActor in
try await updateActivity(state: cached.state, staleDate: cached.staleDate, alert: cached.alert)
}
}
} catch let error as ActivityAuthorizationError {
#warning("TODO: 处理ActivityAuthorizationError各种错误场景")
// switch error {
// case .attributesTooLarge:
// <#code#>
// case .unsupported:
// <#code#>
// case .denied:
// <#code#>
// case .globalMaximumExceeded:
// <#code#>
// case .targetMaximumExceeded:
// <#code#>
// case .unsupportedTarget:
// <#code#>
// case .visibility:
// <#code#>
// case .persistenceFailure:
// <#code#>
// case .missingProcessIdentifier:
// <#code#>
// case .unentitled:
// <#code#>
// case .malformedActivityIdentifier:
// <#code#>
// case .reconnectNotPermitted:
// <#code#>
// }
os_log("%@", type: .error, "ActivityAuthorizationError: \(error.localizedDescription)")
} catch {
let errorMessage = """
!!!!! Couldn't start activity
------------------------
\(String(describing: error))
"""
#warning("TODO: 处理非ActivityAuthorizationError的错误场景")
os_log("%@", type: .error, errorMessage)
}
}
func observeUpdates(activity: Activity<LiveActivityAttributes>) {
Task {
await withTaskGroup(of: Void.self) { group in
group.addTask { @MainActor in
for await enabled in ActivityAuthorizationInfo().activityEnablementUpdates {
os_log("%@", type: .debug, "activityEnablementUpdates: \(enabled)")
}
}
group.addTask { @MainActor in
for await activity in Activity<LiveActivityAttributes>.activityUpdates {
os_log("%@", type: .debug, "activityUpdates: \(activity.attributes)")
}
}
group.addTask { @MainActor in
for await activityState in activity.activityStateUpdates {
os_log("%@", type: .debug, "activityStateUpdates: \(activity), \(activityState)")
if activityState == .dismissed {
// self.cleanUpDismissedActivity()
os_log(.debug, "activity dismissed")
} else {
// self.activityViewState?.activityState = activityState
}
}
}
group.addTask { @MainActor in
for await contentState in activity.contentUpdates {
os_log("%@", type: .debug, "contentUpdates: \(activity), \(contentState)")
// self.activityViewState?.contentState = contentState.state
}
}
group.addTask { @MainActor in
for await pushToken in activity.pushTokenUpdates {
let pushTokenString = pushToken.hexadecimalString
Logger().debug("New push token: \(pushTokenString)")
do {
let frequentUpdateEnabled = ActivityAuthorizationInfo().frequentPushesEnabled
try await self.sendPushToken(id: activity.id,
pushTokenString: pushTokenString,
frequentUpdateEnabled: frequentUpdateEnabled)
} catch {
let errorMessage = """
Failed to send push token to server
------------------------
\(String(describing: error))
"""
os_log("%@", type: .error, "pushTokenUpdates: \(activity), \(errorMessage)")
#warning("TODO: 处理pushTokenUpdates错误场景")
}
}
}
}
}
}
func updateActivity(
state: LiveActivityAttributes.ContentState,
staleDate: Date? = nil,
alert: (title: String, body: String)? = nil
) async throws {
try await Task.sleep(for: .seconds(1))
guard let activity = currentActivity else {
os_log(.debug, "!!!!! no currentActivity")
latestCachedState = .init(state: state, staleDate: staleDate, alert: alert)
return
}
latestCachedState = nil
os_log("%@", type: .debug, "!!!!! updateActivity\nstate: \(state)\nstaleDate:\(staleDate)\nalert:\(alert)")
Task { @MainActor in
var alertConfig: AlertConfiguration?
if let alert {
alertConfig = AlertConfiguration(
title: LocalizedStringResource(stringLiteral: alert.title),
body: LocalizedStringResource(stringLiteral: alert.body),
sound: .default
)
}
await activity.update(
ActivityContent<LiveActivityAttributes.ContentState>(
state: state,
staleDate: staleDate,
relevanceScore: alertConfig != nil ? 100 : 50
),
alertConfiguration: alertConfig
)
}
}
func endActivity(finalState: LiveActivityAttributes.ContentState, dismissalPolicy: ActivityWidgetDismissalPolicy) {
guard let activity = currentActivity else {
os_log(.debug, "!!!!! no currentActivity")
return
}
os_log("%@", type: .debug, "!!!!! endActivity\nfinalState: \(finalState)\ndismissalPolicy:\(dismissalPolicy)")
let policy: ActivityUIDismissalPolicy
switch dismissalPolicy {
case .default: policy = .default
case .immediate: policy = .immediate
case .after(let date): policy = .after(date)
}
Task { @MainActor in
await activity.end(ActivityContent(state: finalState, staleDate: finalState.endTime), dismissalPolicy: policy)
}
}
}
private extension ActivityController {
func sendPushToken(id: String, pushTokenString: String, frequentUpdateEnabled: Bool = false) async throws {
// 处理推送相关的逻辑
}
}
private extension Data {
var hexadecimalString: String {
self.reduce("") {
$0 + String(format: "%02x", $1)
}
}
}