在我们的应用程序中,我们查询HealthKit以获取连续7天的步骤计数,每天汇总一次,以午夜为中心。因此范围是D-6午夜到明天的午夜(因为我们想要今天的步骤直到现在)。
是这样吗,我们始终能够获取过去6天的数据,但今天的数据始终为0。
但是奇怪的是,如果我们随后打开iOS 8.0附带的默认iHealth应用程序,它将计算运行状况数据并在图表中显示今天的步骤。然后,如果我们重新打开应用程序并重新加载图表数据,那么今天的步骤简直就是奇迹般的,与“iHealth”显示的内容相匹配。
那么,iPhone是否仅在午夜自动生成每日步数并对其进行缓存?在检索任何健康指标之前,我们是否需要单独打电话以计算今天的数据或其他数据?
这是我们用来获取数据的函数:
func queryDailyStats(metric: NSString!, handler: ([NSDate: Int] -> Void)!) {
let quantityType = HKObjectType.quantityTypeForIdentifier(metric)
let calendar = NSCalendar.currentCalendar()
let now = NSDate()
let preservedComponents: NSCalendarUnit = (.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay)
let midnight: NSDate! = calendar.dateFromComponents(calendar.components(preservedComponents, fromDate:now))
let dailyInterval = NSDateComponents()
dailyInterval.day = 1
let tomorrow = calendar.dateByAddingUnit(.MonthCalendarUnit, value: 1, toDate: midnight, options: nil)
let oneMonthAgo = calendar.dateByAddingUnit(.MonthCalendarUnit, value: -1, toDate: midnight, options: nil)
let oneWeekAgo = calendar.dateByAddingUnit(.DayCalendarUnit, value: -6, toDate: midnight, options: nil) // only need to start from 6 days back
// need tomorrow's midnight as end date to get all of today's data
let predicate = HKQuery.predicateForSamplesWithStartDate(oneWeekAgo, endDate: tomorrow, options: .None)
let query = HKStatisticsCollectionQuery(
quantityType: quantityType,
quantitySamplePredicate: predicate,
options: .CumulativeSum,
anchorDate: midnight,
intervalComponents: dailyInterval
)
query.initialResultsHandler = { query, results, error -> Void in
var data:[NSDate: Int] = [:]
if error != nil {
println(error)
} else {
results.enumerateStatisticsFromDate(oneWeekAgo, toDate: midnight) { statistics, stop in
if let quantity = statistics.sumQuantity() {
let date = statistics.startDate
let value = Int(quantity.doubleValueForUnit(HKUnit.countUnit()))
data[date] = value
}
}
}
handler(data)
}
self.healthKitStore.executeQuery(query)
}
最佳答案
尝试使用此代码,您只需更改开始日期和结束日期即可。
-(void) getQuantityResult
{
NSInteger limit = 0;
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:currentDate endDate:[[NSDate date]dateByAddingTimeInterval:60*60*24*3] options:HKQueryOptionStrictStartDate];
NSString *endKey = HKSampleSortIdentifierEndDate;
NSSortDescriptor *endDate = [NSSortDescriptor sortDescriptorWithKey: endKey ascending: NO];
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]
predicate: predicate
limit: limit
sortDescriptors: @[endDate]
resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
// sends the data using HTTP
int dailyAVG = 0;
for(HKQuantitySample *samples in results)
{
dailyAVG += [[samples quantity] doubleValueForUnit:[HKUnit countUnit]];
}
lblPrint.text = [NSString stringWithFormat:@"%d",dailyAVG];
NSLog(@"%@",lblPrint.text);
NSLog(@"%@",@"Done");
});
}];
[self.healthStore executeQuery:query];
}
关于ios - iOS HealthKit今天的步数始终为0(但可以连续几天),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29708829/