I'm trying to get the sleep duration from the health app, I've authorised it, I've checked the code ,but whatever I do I always get "Not Found"
Here is what I wrote :
func getSleep() {
// first, we define the object type we want
if let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) {
// Use a sortDescriptor to get the recent data first
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
// we create our query with a block completion to execute
let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
if error != nil {
// something happened
return
}
if let result = tmpResult {
// do something with my data
for item in result {
if let sample = item as? HKCategorySample {
let value = (sample.value == HKCategoryValueSleepAnalysis.inBed.rawValue) ? "Not Found" : "Asleep"
print("Duration : \(value)")
DispatchQueue.main.async {
self.stepsLbl.text = "Sleep : \(value)"
}
print("Healthkit sleep: \(sample.startDate) \(sample.endDate) - value: \(value)")
}
}
}
}
// finally, we execute our query
healthStore.execute(query)
}
}
What should I do ?