我今天使用以下代码从 healthkit 获取步骤。
func retrieveStepCount(completion: (stepRetrieved: Double) -> Void) {
let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(NSDate())
let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today
let interval: NSDateComponents = NSDateComponents()
interval.day = 1
let query = HKStatisticsCollectionQuery(quantityType: type!, quantitySamplePredicate: predicate, options: .CumulativeSum, anchorDate: newDate as NSDate, intervalComponents:interval as NSDateComponents)
query.initialResultsHandler = { query, results, error in
if error != nil {
print("Something went Wrong")
return
}
if let myResults = results{
myResults.enumerateStatisticsFromDate(newDate, toDate: NSDate()) {
statistics, stop in
if let quantity = statistics.sumQuantityForSource(HKSource.defaultSource()) {
let steps = quantity.doubleValueForUnit(HKUnit.countUnit())
print("Steps = \(Int(steps))")
completion(stepRetrieved: steps)
}
}
}
}
executeQuery(query)
}
现在假设我总共有这些步骤
从中我有一些由设备自动检测到的步骤。有些是由其他应用程序添加到 heathkit 的。
我确实想要它们,并且我都得到了它们,但是当用户对 healthkit 进行一些手动步骤时,问题就来了。
我不想让这些手动添加的步骤。所以基本上我想得到 (5,793 - 2300) = 3493 步。
我怎样才能做到这一点 ?我试图获取 HKSource 的名称我知道当用户手动输入步骤时,源的名称是“健康”但是我如何在这个基础上过滤步骤?请指导我,我在这里缺少什么?提前致谢