我使用 Xcode 14 为 iOS 16.2 和 WatchOS 9.1 创建了一个自定义/学习者 iOS 应用程序和手表应用程序。这些应用程序有一个真实世界的用户。这些应用程序使用 CoreData 在本地存储活动。应用程序使用 WCSession transferUserInfo() 将新活动的 JSON 表示传输到对应设备,然后对应设备将新活动保存到其 CoreData 数据库。这很好用,应用程序视图动态更新。
使用 Xcode,我添加了手表小部件扩展的目标并稍微更新了样板代码,如下所示。该并发症作为手表应用程序的链接。
接下来我想在将新活动添加到手表应用程序时更新复杂功能(这将包括从 iOS 应用程序传输的活动)。用户每 3 到 8 小时添加一次活动,所以我认为设置未来进入日期的时间表没有意义。并发症只需要最近活动的时间,以便它可以显示自该活动以来经过的时间。
具体来说,当该值更新时,我如何将最近活动的 activityTime 从手表应用程序发送到复杂功能?
import WidgetKit
import SwiftUI
import OSLog
struct Provider: TimelineProvider {
let logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "", category: "Provider")
func placeholder(in context: Context) -> mostRecentActivityEntry {
mostRecentActivityEntry(date: Date(), activityTime: Date())
}
func getSnapshot(in context: Context, completion: @escaping (mostRecentActivityEntry) -> ()) {
let entry = mostRecentActivityEntry(date: Date(), activityTime: Date())
completion(entry)
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
var mostRecentActivityTime: Date?
var entries: [mostRecentActivityEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = mostRecentActivityEntry(date: entryDate, activityTime: mostRecentActivityTime)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct mostRecentActivityEntry: TimelineEntry {
var date: Date
var activityTime: Date?
}
struct MostRecentEntryView : View {
var entry: Provider.Entry
var body: some View {
HStack {
Text("Log")
.font(.headline)
.foregroundColor(.purple)
if let time = entry.activityTime {
Text(time, style: .relative)
.font(.headline)
.foregroundColor(.accentColor)
}
Spacer()
}
}
}
@main
struct ActivityLogWatchWidgetExtension: Widget {
let kind: String = "ActivityLogWatchWidgetExtension"
var body: some WidgetConfiguration {
StaticConfiguration(
kind: kind,
provider: Provider()) { entry in
MostRecentEntryView(entry: entry)
}
.configurationDisplayName("Time Since Last Activity")
.description("Displays the time since the last activity.")
}
}
struct ActivityLogWatchWidgetExtension_Previews: PreviewProvider {
static var previews: some View {
MostRecentEntryView(entry: mostRecentActivityEntry(date: Date(), activityTime: Date().addingTimeInterval(-1000)))
.previewContext(WidgetPreviewContext(family: .accessoryRectangular))
MostRecentEntryView(entry: mostRecentActivityEntry(date: Date(), activityTime: nil))
.previewContext(WidgetPreviewContext(family: .accessoryRectangular))
}
}