IOS实现基于CMPedometer的计步器

  

CMStepCount类在IOS8已经不推荐使用了,IOS8推荐使用CMPedometer类来处理用户健康和运动信息。下面是一个小小的演示来演示下,如何使用它,以及一些注意事项。

        #进口“ViewController.h”   # import & lt; CoreMotion/CoreMotion.h>      @ interface ViewController ()      @ property(弱,原子)IBOutlet UILabel * stepLabel;   @ property(原子、强)CMPedometer * stepter;   @ property(弱,原子)IBOutlet UILabel * totalLabel;      @end      @ implementation ViewController      - (void) viewDidLoad {   (超级viewDidLoad);      如果(![CMPedometer isStepCountingAvailable])   {   NSLog(@“计步器不可用”);   返回;   }      _stepter=[[CMPedometer alloc] init);      NSTimeInterval secondsPerDay=24 * 60 * 60;   NSDate *日期=(NSDate日期);   昨天NSDate *=[日期dateByAddingTimeInterval -secondsPerDay):;         [_stepter startPedometerUpdatesFromDate:昨天withHandler: ^ (CMPedometerData * _Nullable pedometerData, NSError * _Nullable错误){         如果(错误)   {   NSLog(@“错误==% @”,错误);   其他}   {   NSNumber *步骤=pedometerData.numberOfSteps;   NSNumber *距离=pedometerData.distance;      NSDictionary * dic=@ {   @“步骤”:步骤,   @“距离”:距离   };      NSLog(@”过去一天你一共走了% @步,一共% @米”,步骤,距离);      【自我performSelectorOnMainThread: @ selector (refreshUI:) withObject: dic waitUntilDone:没有);      }      });      }      - (void) refreshUI: (NSDictionary *) dic   {   NSNumber *距离=dic[@“距离”);   浮动米=(距离floatValue);      self.stepLabel。文本=[NSString stringWithFormat: @ % @, dic[@“步骤”]];   self.totalLabel。文本=[NSString stringWithFormat: @ % .2f,米);   }      - (void) didReceiveMemoryWarning {   (超级didReceiveMemoryWarning);//处理任何资源都可以被重新创建。   }         @end      

此处还有一点需要注意:就是请在info.plist文件中加入你要访问用户健康和运动信息的描述,如下图

  

 IOS实现基于CMPedometer的计步器

  

运行结果如下:

  

 IOS实现基于CMPedometer的计步器

  

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

IOS实现基于CMPedometer的计步器