From 5950ca738bb4b12e46824d686b6fcbbaa86162d3 Mon Sep 17 00:00:00 2001 From: Trey t Date: Sat, 20 Dec 2025 01:03:06 -0600 Subject: [PATCH] Speed up HealthKit sync with batch saves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Save 100 samples at a time instead of individually. Removes per-entry delays and uses healthStore.save([batch]) for much faster throughput. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- Shared/HealthKitManager.swift | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/Shared/HealthKitManager.swift b/Shared/HealthKitManager.swift index 6021671..7a5c787 100644 --- a/Shared/HealthKitManager.swift +++ b/Shared/HealthKitManager.swift @@ -126,25 +126,36 @@ class HealthKitManager: ObservableObject { return } + // Create all samples upfront + let samples: [HKStateOfMind] = validEntries.map { entry in + HKStateOfMind( + date: entry.forDate, + kind: .dailyMood, + valence: moodToValence(entry.mood), + labels: labelsForMood(entry.mood), + associations: [.currentEvents] + ) + } + + // Save in batches for better performance + let batchSize = 100 var successCount = 0 var failCount = 0 - for (index, entry) in validEntries.enumerated() { + for batchStart in stride(from: 0, to: samples.count, by: batchSize) { + let batchEnd = min(batchStart + batchSize, samples.count) + let batch = Array(samples[batchStart.. 0 { - try? await Task.sleep(nanoseconds: 50_000_000) // 50ms - } } isSyncing = false