The app has permissions from the health app for sleep data. I am currently able to pull step count and heart rate but sleep data shows as 0. Here is the code I have to retrieve sleep data. Please let me know if I am doing something wrong or missing something.
func fetchSleepData() {
let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)!
let startDate = Calendar.current.startOfDay(for: Date())
let endDate = Date()
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { query, samples, error in
guard let samples = samples as? [HKCategorySample], error == nil else {
print("Failed to fetch sleep data: \(error?.localizedDescription ?? "No error")")
return
}
// Calculate total sleep duration using .allAsleepValues
let totalSleep = samples.reduce(0.0) { sum, sample in
if HKCategoryValueSleepAnalysis.allAsleepValues.contains(HKCategoryValueSleepAnalysis(rawValue: sample.value) ?? .awake) {
let sleepDuration = sample.endDate.timeIntervalSince(sample.startDate)
return sum + sleepDuration
}
return sum
}
let sleepHours = totalSleep / 3600.0 // Convert seconds to hours
print("Total Sleep Hours: \(sleepHours)")
// Send Data to Backend
self.sendDataToServer(data: ["sleep_hours": sleepHours])
}
healthStore.execute(query)
}
I'm going to guess that this is merely an authorization issue. I ran your code and got 27 samples with a value of 13500 for totalSleep
. So your code, as it stands, works just fine (in the sense that it gets values). But if I then turn off authorization for Sleep under Health in Settings, and run your code again, I get zero, matching your results.