iOS 提供 CoreMotion 框架,其中 CMStepCounter 可用來取得裝置的步行步數。以下範例展示如何建立計步器,並將步數顯示在 UILabel 上。
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
@property (nonatomic, strong) CMStepCounter *counter;
@property (weak, nonatomic) IBOutlet UILabel *stepLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if (![CMStepCounter isStepCountingAvailable]) {
return;
}
[self.counter startStepCountingUpdatesToQueue:[NSOperationQueue mainQueue] updateOn:5 withHandler:^(NSInteger numberOfSteps, NSDate *timestamp, NSError *error) {
self.stepLabel.text = [NSString stringWithFormat:@"一共走了%ld步", (long)numberOfSteps];
}];
}
- (CMStepCounter *)counter {
if (_counter == nil) {
_counter = [[CMStepCounter alloc] init];
}
return _counter;
}
@end
效果如下:

使用時需先確認裝置是否支援計步功能。此外,updateOn 參數可控制更新頻率,可依畫面需求調整。