feat: 完善饮水 widget
This commit is contained in:
@@ -7,12 +7,68 @@
|
||||
|
||||
import WidgetKit
|
||||
import AppIntents
|
||||
import Foundation
|
||||
|
||||
struct ConfigurationAppIntent: WidgetConfigurationIntent {
|
||||
static var title: LocalizedStringResource { "Configuration" }
|
||||
static var description: IntentDescription { "This is an example widget." }
|
||||
|
||||
// An example configurable parameter.
|
||||
@Parameter(title: "Favorite Emoji", default: "😃")
|
||||
var favoriteEmoji: String
|
||||
static var title: LocalizedStringResource { "Water Widget Configuration" }
|
||||
static var description: IntentDescription { "Configure water intake widget settings." }
|
||||
}
|
||||
|
||||
// Intent for adding water record
|
||||
struct AddWaterIntent: AppIntent {
|
||||
static var title: LocalizedStringResource { "Add Water" }
|
||||
static var description: IntentDescription { "Add water intake record" }
|
||||
|
||||
@Parameter(title: "Amount (ml)")
|
||||
var amount: Int
|
||||
|
||||
init(amount: Int) {
|
||||
self.amount = amount
|
||||
}
|
||||
|
||||
init() {
|
||||
self.amount = 150 // default value
|
||||
}
|
||||
|
||||
func perform() async throws -> some IntentResult {
|
||||
// Add water directly through shared UserDefaults
|
||||
guard let sharedDefaults = UserDefaults(suiteName: "group.com.anonymous.digitalpilates") else {
|
||||
print("Failed to access App Group UserDefaults")
|
||||
return .result()
|
||||
}
|
||||
|
||||
// Get current values
|
||||
let currentIntake = sharedDefaults.object(forKey: "widget_current_water_intake") as? Int ?? 0
|
||||
let targetIntake = sharedDefaults.object(forKey: "widget_daily_water_goal") as? Int ?? 2000
|
||||
|
||||
// Update current intake
|
||||
let newIntake = currentIntake + amount
|
||||
sharedDefaults.set(newIntake, forKey: "widget_current_water_intake")
|
||||
|
||||
// Create ISO8601 formatted date string
|
||||
let formatter = ISO8601DateFormatter()
|
||||
let isoString = formatter.string(from: Date())
|
||||
sharedDefaults.set(isoString, forKey: "widget_last_sync_time")
|
||||
sharedDefaults.synchronize()
|
||||
|
||||
print("Water added from widget: +\(amount)ml, New total: \(newIntake)ml")
|
||||
|
||||
// 设置待同步标记,主应用启动时会检测并同步到 TypeScript/Redux
|
||||
let pendingRecords = sharedDefaults.array(forKey: "widget_pending_water_records") as? [[String: Any]] ?? []
|
||||
let newRecord: [String: Any] = [
|
||||
"amount": amount,
|
||||
"recordedAt": isoString,
|
||||
"source": "auto",
|
||||
"widgetAdded": true
|
||||
]
|
||||
let updatedRecords = pendingRecords + [newRecord]
|
||||
sharedDefaults.set(updatedRecords, forKey: "widget_pending_water_records")
|
||||
|
||||
// Trigger widget refresh
|
||||
WidgetCenter.shared.reloadTimelines(ofKind: "WaterWidget")
|
||||
|
||||
print("水记录已添加到待同步队列,主应用启动时将同步到 Redux Store")
|
||||
|
||||
return .result()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user