I'm building an application for sleep analysis using Apple Healthkit and wish to retrieve nightly sleep statistics (time in REM, deep, light etc). The apple developer video gives the following code to retrieve samples in all sleep stages...
let stagePredicate = HKCategoryValueSleepAnalysis.predicateForSamples(equalTo: .allAsleepValues)
let queryPredicate = HKSamplePredicate.sample(type: HKCategoryType(.sleepAnalysis), predicate: stagePredicate)
let sleepQuery = HKSampleQueryDescriptor(predicates: [queryPredicate], sortDescriptors: [])
// Run the query
let sleepSamples = try async sleepQuery.result(for: healthStore)
but how do I compute the time in each of the stages for the previous night? I'm very new to healthkit so any help would be appreciated.
To compute the time in each stage you'll want to iterate over the samples and check the category value. You can keep a time interval per stage and increment it based on the duration of the sample you're looking at.
The tricky part is determining what "previous night" is. Try defining equally sized buckets where you will count all samples in that bucket as part of the same "sleep session" (e.g. 6pm - 6pm instead of 12am - 12am).