自iOS7以来,Apple官方API给开发者提供了单独的类来查询一定时间内的健康数据统计,比如步数。
CMStepCounter
这是一个自iOS7开始可以使用的类,但是在iOS8中即被舍弃,换用了新的类CMPedometer来替换其功能的实现。
尽管如此,其在iOS7设备上进行数据采集还是很重要:
if (!([CMStepCounter isStepCountingAvailable] || [CMMotionActivityManager isActivityAvailable])) {
return;
}
self.operationQueue = [[NSOperationQueue alloc] init];
//更新label
if ([CMStepCounter isStepCountingAvailable])
{
self.stepCounter = [[CMStepCounter alloc] init];
[self.stepCounter startStepCountingUpdatesToQueue:self.operationQueue updateOn:2 withHandler:^(NSInteger numberOfSteps, NSDate *timestamp, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
if (error){
UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"获取步数出错" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[error show];
}else {
self.autoSteps = numberOfSteps;
DebugLog(@"%@", [NSString stringWithFormat:@"Step count: %d", self.autoSteps]);
}
});
}];
}
}
CMPedometer
这是一个在iOS8以后替代上面记步类实现采集数据的功能。
- (void)startPedometerUpdatesFromDate:(NSDate *)start withHandler:(CMPedometerHandler)handler;
- (void)queryPedometerDataFromDate:(NSDate *)start toDate:(NSDate *)end withHandler:(CMPedometerHandler)handler;
CMPedometer *pedometer = [[CMPedometer alloc]init];
//判断记步功能
if ([CMPedometer isStepCountingAvailable]) {
[pedometer startPedometerUpdatesFromDate:[NSDate date] withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
//
if (error) {
NSLog(@"error = %@",error);
} else {
NSLog(@"%@",pedometerData);
}
}];
}else{
NSLog(@"记步功能不可用");
}