HealthKit Swift getting today's steps

后端 未结 6 1499
灰色年华
灰色年华 2020-12-23 11:50

I am making a swift iOS app that integrates with a user\'s step count as reported by the Health app. I can easily find the user\'s step count in the last hour, using this as

6条回答
  •  梦毁少年i
    2020-12-23 12:47

    HKStatisticsCollectionQuery is better suited to use when you want to retrieve data over a time span. Use HKStatisticsQuery to just get the steps for a specific date.

    Swift 5:

    let healthStore = HKHealthStore()
    
    func getTodaysSteps(completion: @escaping (Double) -> Void) {
        let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
    
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
    
        let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
            guard let result = result, let sum = result.sumQuantity() else {
                completion(0.0)
                return
            }
            completion(sum.doubleValue(for: HKUnit.count()))
        }
    
        healthStore.execute(query)
    }
    

提交回复
热议问题