feat: 完善饮水 widget
This commit is contained in:
81
ios/digitalpilates/WaterRecordManager.swift
Normal file
81
ios/digitalpilates/WaterRecordManager.swift
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user