Apple healthKit REM, Deep, Light sleep analysis
Asked Answered
O

1

7

I am working on an IOS sleep application where i need to do sleep analysis. I am using Healthkit for sleep data from where i can successfully fetch sleep analysis data using below code :

func retrieveSleepAnalysis(from startDate: Date?, to endDate: Date? , completion: @escaping ([HKCategorySample], Error?) -> Void) {
guard let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) else { return}
        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
        let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: 10000, sortDescriptors: [sortDescriptor]) { (query, result, error) in
            if error != nil {
                completion([], error)
                return
            }
            if let result = result {
                let samples = result.compactMap({ $0 as? HKCategorySample})
                completion(samples, nil)
            }
        }
        // finally, we execute our query
        HKHealthStore().execute(query)
    }

I am not able to find any healthKit code for Sleep REM cycles , Deep sleep , light sleep etc. Is it even possible to get this data from healthKit ? if Yes , How to do it? , if not with healthKit, How to do it in IOS Applications ?

Oxfordshire answered 10/6, 2022 at 6:41 Comment(0)
M
5

You may find what you're looking for in this year's WWDC talk on "What's New In HealthKit"

Here's how you can declare a predicate for all samples:

// Predicate for all asleep samples (unspecified, core, deep, REM)
let allAsleepPredicate = HKCategoryValueSleepAnalysis.predicateForSamples(equalTo: .allAsleepValues)

And here's how you might use it to fetch all samples in a range:

let healthStore = HKHealthStore()
let sleepType = HKCategoryType(.sleepAnalysis)

let dateRangePredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [dateRangePredicate, allAsleepPredicate])

let query = HKSampleQuery(sampleType: sleepType, predicate: predicate) { (query, result, error) in
    // handle results
}

Hope that helps

Muckworm answered 10/6, 2022 at 15:50 Comment(4)
Thank you very much @Muckworm for the information. Let me try it out .Oxfordshire
When will we able to use it? , Currently i can check compiler throwing error for this code sample, Do we need to wait for another Swift update as i am already using latest version of xCode?Oxfordshire
It’s in beta so if you have access to the beta versions you can otherwise you will have to wait until it shipsMuckworm
Thanks @JPC, i have to wait at least till September until devices got ios 16.0 update?Oxfordshire

© 2022 - 2024 — McMap. All rights reserved.