IOS

关注公众号 jb51net

关闭
首页 > 软件编程 > IOS > 基于CMPedometer的计步器

IOS实现基于CMPedometer的计步器

作者:ling_fengxue

这篇文章主要为大家详细介绍了IOS实现基于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 =@{ 
                 @"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文件中加入你要访问用户健康和运动信息的描述,如下图

运行结果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文