HealthSyncStateStore.swift
1.1 KB
import Foundation
/// Stores the last successful local HealthKit sync boundary.
/// This is intentionally independent from the old SwiftUI user/network layer.
struct HealthSyncStateStore {
private let defaults: UserDefaults
private let keyPrefix = "native_health_sync_latest_time_"
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
func lastSyncDate(for type: NativeHealthDataType) -> Date? {
let timestamp = defaults.double(forKey: key(for: type))
return timestamp > 0 ? Date(timeIntervalSince1970: timestamp) : nil
}
func save(date: Date, for type: NativeHealthDataType) {
defaults.set(date.timeIntervalSince1970, forKey: key(for: type))
}
func startDate(for type: NativeHealthDataType, fallbackWeeks: Int = 1) -> Date {
if let date = lastSyncDate(for: type) {
return date
}
let fallback = Calendar.current.date(byAdding: .weekOfYear, value: -fallbackWeeks, to: Date())
return Calendar.current.startOfDay(for: fallback ?? Date())
}
private func key(for type: NativeHealthDataType) -> String {
"\(keyPrefix)\(type.rawValue)"
}
}