所以这是我的问题与LiveActivities。我的代码不工作,但没有抛出错误…
下面是我如何启用/禁用活动:
let helper = JourneyActivityHelper.shared
TagComponent(journey: journey)
.onChange(of: journey.isTracked) { value in
journey.isTracked ? helper.start(departureTime: departureTime, arrivalTime: arrivalTime, journey: journey) : helper.stop(departureTime: departureTime, arrivalTime: arrivalTime)
}
这是我的助手类:
struct JourneyAttributes: ActivityAttributes {
public typealias JourneyStatus = ContentState
public struct ContentState: Codable, Hashable {
var departureTime: Date
var arrivalTime: Date
}
var journey: Journey
}
class JourneyActivityHelper {
static let shared = JourneyActivityHelper()
var activity: Activity<JourneyAttributes>?
func start(departureTime: Date, arrivalTime: Date, journey: Journey) {
// We check that activities can be enabled
guard ActivityAuthorizationInfo().areActivitiesEnabled else { return }
// Initializing variables
let initialState = JourneyAttributes.ContentState(departureTime: departureTime, arrivalTime: arrivalTime)
let staleDate = departureTime <= Date() ? nil : departureTime
let initialContent = ActivityContent(state: initialState, staleDate: staleDate)
let attributes = JourneyAttributes(journey: journey)
do {
activity = try Activity.request(attributes: attributes, content: initialContent)
print("New live activity activated!")
} catch (let error) {
print(error.localizedDescription)
}
}
func stop(departureTime: Date, arrivalTime: Date) {
Task {
let finalState = JourneyAttributes.ContentState(departureTime: departureTime, arrivalTime: arrivalTime)
let finalContent = ActivityContent(state: finalState, staleDate: nil)
for activity in Activity<JourneyAttributes>.activities {
await activity.end(finalContent, dismissalPolicy: .immediate)
}
}
}
}
最后,这是我的LiveActivity代码(Widget):
@main
struct TrainlyWidgetBundle: WidgetBundle {
@WidgetBundleBuilder
var body: some Widget {
TrainlyWidget()
if #available(iOS 16.2, *) {
ActivityConfiguration(for: JourneyAttributes.self) { context in
LockScreenLiveActivity(context: context)
} dynamicIsland: { context in
...
}
}
}
}
提前感谢任何人谁可以帮助我解决我的问题!
编辑:我所期望的:我的LiveActivity显示。结果是:它没有出现!
我自己解决了问题。departureTime
和arrivalTime
(传递给start()
和stop()
函数的日期)不是实际日期。因此,Live Activity没有开始,因为日期在过去(2000年而不是2023年)