HealthKit Swift getting today's steps

后端 未结 6 1495
灰色年华
灰色年华 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条回答
  •  自闭症患者
    2020-12-23 12:24

    Using the above answers and from Apple here: https://developer.apple.com/reference/healthkit/hkstatisticsquery I got the following to work in swift 2.3 on Xcode 8.0.

    class func getStepCountHealth(startDate: NSDate, endDate: NSDate, completion:(Double?, NSError?)->()) {
    
                let healthKitStore:HKHealthStore = HKHealthStore()
    
                //   Define the sample type
                let sampleType = HKQuantityType.quantityTypeForIdentifier(
                HKQuantityTypeIdentifierStepCount)
    
                //  Set the predicate
                let predicate = HKQuery.predicateForSamplesWithStartDate(startDate,
                                                                     endDate: endDate, options: .None)
                // build the query
                let sampleQuery = HKStatisticsQuery(quantityType: sampleType!,
                                          quantitySamplePredicate: predicate,
                                          options: .CumulativeSum) { query, results, error in
    
                                            if results != nil {
                                                let quantity = results?.sumQuantity()
                                                let unit = HKUnit.countUnit()
                                                let totalSteps = quantity?.doubleValueForUnit(unit)
                                                completion(totalSteps, error)
    //                                            print("totalSteps for \(endDate) are \(totalSteps!)")
                                            } else {
                                                completion(nil, error)
    //                                            print("results are nil")
                                                return
                                            } 
                                        }
                // execute the Query
                healthKitStore.executeQuery(sampleQuery)
            }
    

提交回复
热议问题