您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

使用 CMStepCounter 實作 iOS 計步器

編輯:iOS 開發綜合

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 參數可控制更新頻率,可依畫面需求調整。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved