写在前面
本人初学ios开发,很多东西可能说的不对,如果客官们发现有纰漏,请联系我,一起讨论。勿喷
准备工作
1.导入框架
CoreMotion.framework
2.在需要进行计步的viewController的.m中导入头文件
#import <CoreMotion/CoreMotion.h>
正式开始
废话不多说,实现很简单,直接上代码
#import "TBViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface TBViewController ()
@property (strong, nonatomic) CMStepCounter *stepCounter;
@end
@implementation TBViewController
- (void)viewDidLoad
{
[super viewDidLoad];
if ([CMStepCounter isStepCountingAvailable]) {
self.stepCounter = [[CMStepCounter alloc] init];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[self.stepCounter startStepCountingUpdatesToQueue:queue updateOn:5 withHandler:^(NSInteger numberOfSteps, NSDate *timestamp, NSError *error) {
self.countLabel.text = [NSString stringWithFormat:@"已经走了%d步", numberOfSteps];
}];
}
else{
self.countLabel.text = @"计步器不可用";
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
更新UI:我是在storyboard中拖了个Label然后获取outlet。
startStepCountingUpdatesToQueue:queue updateOn:5 withHandler:^(NSInteger numberOfSteps, NSDate *timestamp, NSError *error
最后那个block中,numberOfSteps就是sensor检测到你一共走的步数。用这个更新