计步器(CMPedometer) - (Obj-C)

CMStepCounter记录的数据并不准确,iOS 8.0下已经过期,CMPedometer返回的结果更为精准,但是有延迟性

示例代码:

#import "ViewController.h"
#import 

@interface ViewController ()
@property (nonatomic,strong) CMPedometer *pedometer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1. 创建计步器
    self.pedometer = [[CMPedometer alloc]init];
    
    // 2. 开启计步器
    [self.pedometer startPedometerUpdatesFromDate:[NSDate date] withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
        
        
        NSLog(@"%@",pedometerData.numberOfSteps);
    }];
    
}

@end

除了上面的方法获取数据外,还提供了一个方法,可以限定时间内获取计步数据

[self.pedometer queryPedometerDataFromDate:[NSDate date] toDate:[NSDate dateWithTimeIntervalSinceNow:10] withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
        
    NSLog(@"%@",pedometerData.numberOfSteps);
}];

回调中结果返回为一CMPedometerData对象,其中包含属性有:

@property(readonly, nonatomic) NSDate *startDate; 开始时间
@property(readonly, nonatomic) NSDate *endDate;  结束时间
@property(readonly, nonatomic) NSNumber *numberOfSteps; 计步
@property(readonly, nonatomic, nullable) NSNumber *distance; 距离
@property(readonly, nonatomic, nullable) NSNumber *floorsAscended;上了多少台阶
@property(readonly, nonatomic, nullable) NSNumber *floorsDescended;下了多少台阶
@property(readonly, nonatomic, nullable) NSNumber *currentPace;步速 s/m
@property(readonly, nonatomic, nullable) NSNumber *currentCadence;节奏steps/s

你可能感兴趣的:(计步器(CMPedometer) - (Obj-C))