Search code examples
swifthealthkit

Health Kit steps by movement for the day separated by device type


How to get data like in image below in Swift, im calculating steps per day and steps per hour but not sure how to get like below. I would like to get by device(watch, phone) steps per movement group not by a time interval?

enter image description here


Solution

  • I used HKSampleQuery

    func getStepCountForTodaySegmentedByMovement( complete: @escaping ([HKCumulativeQuantitySample]) -> () ) {
            let healthStore = HKHealthStore()
            
            guard let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount) else {
                fatalError("*** Unable to create a step count type ***")
            }
            
            let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: .distantFuture, options: .strictEndDate)
    
            
            let query = HKSampleQuery(sampleType: stepsQuantityType,
                                                    predicate: predicate,
                                                    limit: HKObjectQueryNoLimit,
                                                    sortDescriptors: [NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true)]) {
                (query, results, error) in
                
                
                complete(results as? [HKCumulativeQuantitySample] ?? [])
            }
            
            healthStore.execute(query)
          
        }