import SpikeSDK
// Example: Backfill last 7 days of steps data
let calendar = Calendar.current
let today = Date()
for dayOffset in 0..<7 {
guard let startDate = calendar.date(byAdding: .day, value: -dayOffset, to: today) else { continue }
guard let endDate = calendar.date(byAdding: .day, value: 1, to: startDate) else { continue }
do {
let statistics = try await spikeConnection.getStatistics(
ofTypes: [.steps],
from: startDate,
to: endDate,
interval: .day,
filter: StatisticsFilter(providers: [.apple])
)
// Process the statistics data
for statistic in statistics {
print("Steps for \(statistic.start): \(statistic.value)")
}
} catch {
// Handle specific error types for better user experience
if let hkError = error as? HKError {
switch hkError.code {
case .errorAuthorizationNotDetermined:
print("Authorization not determined. Request permissions first.")
case .errorAuthorizationDenied:
print("Access denied. Guide user to Health app settings.")
default:
print("HealthKit error: \(hkError.localizedDescription)")
}
} else {
print("Error fetching statistics for \(startDate): \(error.localizedDescription)")
}
}
}