Files
digital-pilates/ios/WaterWidget/AppIntent.swift
2025-09-09 14:26:16 +08:00

75 lines
2.6 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// AppIntent.swift
// WaterWidget
//
// Created by richard on 2025/9/9.
//
import WidgetKit
import AppIntents
import Foundation
struct ConfigurationAppIntent: WidgetConfigurationIntent {
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()
}
}