I am querying Apple HealthKit for sleep analysis using HKCategoryType(.sleepAnalysis) per the documentation. My query is returning samples for the majority of dates and I am performing analysis based on this successfully. However there are instances where the native apple health/sleep app shows sleep samples for a specific date, but when I query the health store directly for the same date range I get nil per the below:
(Example of printing query, results and error to the console)
'''
Query -> HKSampleQuery QoS=Default state=deactivated
Results -> Optional([])
Error -> nil
'''
My Query to the healthStore:
let startDate = Calendar.current.date(byAdding: .hour, value: -12, to: Date().startOfDay())! // 12 midday yesterday
let endDate = Calendar.current.date(byAdding: .hour, value: -12, to: Date().endOfDay())! // Midday today
let healthStore: HKHealthStore = HKHealthStore()
func fetchSleepDataFor(
sleepTypes: [HealthKitSleepType],
startDate: Date,
endDate: Date,
completion: @escaping ([HealthKitSleepSession]
) -> Void) {
let dispatchGroup = DispatchGroup()
var sleepSessions: [HealthKitSleepSession] = []
let sleepType = HKCategoryType(.sleepAnalysis)
let dateRangePredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [.strictEndDate])
dispatchGroup.enter()
let query = HKSampleQuery(
sampleType: sleepType,
predicate: dateRangePredicate,
limit: HKObjectQueryNoLimit,
sortDescriptors: nil
) { (query, results, error) in
print(query)
print(results)
print(error)
}
healthStore.execute(query)
}
Given I can see the sleep samples and analysis in the native apple health app for the specific date range I would expect them to be present when I directly query them from the healthStore too. I have browsed around the documentation and forums for any mention of this happening but haven't managed to come across anything.
I have performed the following and so I don't think any are the root of the issue:
- Successful request for HealthKitAuthorization from user
- Enabled read and write access to HKObjectType.categoryType(forIdentifier: .sleepAnalysis)
Any guidance as to why this might be the case would be helpful