您的位置:首页 > 移动开发 > IOS开发

iOS - 计步器

2016-05-01 17:39 489 查看
一、导入框架

#import <CoreMotion/CoreMotion.h>
二、添加了两个属性

/** 计步器对象 */
@property(nonatomic, strong) CMStepCounter *counter;
/** 记录步数的label */
@property (weak, nonatomic) IBOutlet UILabel *stepLabel;
三、懒加载

#pragma mark - 懒加载代码
-(CMStepCounter *)counter
{
if (_counter == nil) {
_counter = [[CMStepCounter alloc] init];
}
return _counter;
}


四、计步

- (void)viewDidLoad {
[super viewDidLoad];

// 1.判断计步器是否可用
if (![CMStepCounter isStepCountingAvailable]) {
NSLog(@"计步器不可用");
return;
}

// 2.开始计步
/** 当用户大概走了updateOn步后,回调block */
[self.counter startStepCountingUpdatesToQueue:[NSOperationQueue mainQueue] updateOn:5 withHandler:^(NSInteger numberOfSteps, NSDate * _Nonnull timestamp, NSError * _Nullable error) {
if (error) return;

self.stepLabel.text = [NSString stringWithFormat:@"您一共走了%ld步", numberOfSteps];

// 如果是子队列,不要在这里直接更新,请使用下面的方法回到主队列再进行数据更新
// self.stepLabel performSelectorOnMainThread:<#(nonnull SEL)#> withObject:<#(nullable id)#> waitUntilDone:<#(BOOL)#>
}];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios