溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

IOS實(shí)現(xiàn)基于CMPedometer的計(jì)步器

發(fā)布時(shí)間:2020-10-06 14:30:41 來源:腳本之家 閱讀:128 作者:ling_fengxue 欄目:移動(dòng)開發(fā)

CMStepCount類在IOS8已經(jīng)不推薦使用了,IOS8推薦使用CMPedometer類來處理用戶健康和運(yùn)動(dòng)信息.下面是一個(gè)小小的demo來演示下,如何使用它,以及一些注意事項(xiàng).

#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(@"計(jì)步器不可用"); 
    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 

此處還有一點(diǎn)需要注意:就是請(qǐng)?jiān)趇nfo.plist文件中加入你要訪問用戶健康和運(yùn)動(dòng)信息的描述,如下圖

IOS實(shí)現(xiàn)基于CMPedometer的計(jì)步器

運(yùn)行結(jié)果如下:

IOS實(shí)現(xiàn)基于CMPedometer的計(jì)步器

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI