feat: 完善饮水 widget

This commit is contained in:
richarjiang
2025-09-09 14:26:16 +08:00
parent cacfde064f
commit e56ebe3636
13 changed files with 984 additions and 62 deletions

View File

@@ -0,0 +1,81 @@
//
// WaterRecordManager.swift
// digitalpilates
//
// Native module for managing water records through React Native bridge
//
import Foundation
import React
import WidgetKit
@objc(WaterRecordManager)
class WaterRecordManager: NSObject, RCTBridgeModule {
static func moduleName() -> String! {
return "WaterRecordManager"
}
static func requiresMainQueueSetup() -> Bool {
return false
}
@objc
func addWaterRecord(_ amount: Int, resolver: @escaping RCTPromiseResolveBlock, rejecter: @escaping RCTPromiseRejectBlock) {
// App Group UserDefaults Widget
guard let sharedDefaults = UserDefaults(suiteName: "group.com.anonymous.digitalpilates") else {
rejecter("USERDEFAULTS_ERROR", "Failed to access App Group UserDefaults", nil)
return
}
let currentIntake = sharedDefaults.object(forKey: "widget_current_water_intake") as? Int ?? 0
let newIntake = currentIntake + amount
sharedDefaults.set(newIntake, forKey: "widget_current_water_intake")
// ISO8601
let formatter = ISO8601DateFormatter()
let isoString = formatter.string(from: Date())
sharedDefaults.set(isoString, forKey: "widget_last_sync_time")
sharedDefaults.synchronize()
print("Water record added via bridge: +\(amount)ml, New total: \(newIntake)ml")
// React Native bridge TypeScript
DispatchQueue.main.async { [weak self] in
guard let bridge = self?.bridge else {
rejecter("BRIDGE_ERROR", "React Native bridge is not available", nil)
return
}
// TypeScript Redux action
let eventData = [
"amount": amount,
"recordedAt": isoString,
"source": "auto" // Widget/
]
// TypeScript
self?.sendEvent(withName: "WaterRecordAdded", body: eventData)
// Widget
if #available(iOS 14.0, *) {
WidgetCenter.shared.reloadTimelines(ofKind: "WaterWidget")
}
resolver(["success": true, "amount": amount, "newTotal": newIntake])
}
}
// MARK: - Event Emitter
override func supportedEvents() -> [String]! {
return ["WaterRecordAdded"]
}
private func sendEvent(withName name: String, body: Any) {
if let bridge = self.bridge {
bridge.eventDispatcher().sendAppEvent(withName: name, body: body)
}
}
}