1. 程式人生 > >基於CMPedometer的計步器

基於CMPedometer的計步器

CMStepCount類在IOS8已經不推薦使用了,IOS8推薦使用CMPedometer類來處理使用者健康和運動資訊.下面是一個小小的demo來演示下,如何使用它,以及一些注意事項.

#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *stepLabel;
@property(nonatomic,strong) CMPedometer *stepter;
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if(![CMPedometer isStepCountingAvailable])
    {
        NSLog(@"計步器不可用");
        return;
    }
    
    _stepter =[[CMPedometer alloc]init];
    
    NSTimeInterval secondsPerDay =24*60*60;
    NSDate *date =[NSDate date];
    NSDate *yesterDay =[date dateByAddingTimeInterval:-secondsPerDay];
    
    
    [_stepter startPedometerUpdatesFromDate:yesterDay withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
        
        
        if(error)
        {
            NSLog(@"error ==%@",error);
        }else
        {
            NSNumber *steps =pedometerData.numberOfSteps;
            NSNumber *distance =pedometerData.distance;
            
            NSDictionary *dic 
[email protected]
{ @"steps":steps, @"distance":distance }; NSLog(@"過去一天你一共走了%@步,一共%@米",steps,distance); [self performSelectorOnMainThread:@selector(refreshUI:) withObject:dic waitUntilDone:NO]; } }]; } -(void)refreshUI:(NSDictionary *)dic { NSNumber *distance =dic[@"distance"]; float meters =[distance floatValue]; self.stepLabel.text =[NSString stringWithFormat:@"%@",dic[@"steps"]]; self.totalLabel.text =[NSString stringWithFormat:@"%.2f",meters]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end


此處還有一點需要注意:就是請在info.plist檔案中加入你要訪問使用者健康和運動資訊的描述,如下圖



執行結果如下: