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

81 lines
2.5 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.

//
// 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)
}
}
}