iPhone5s 或者更新的机型,有协处理器,可以在消耗很低的电量的情况下,记录手机上传感器获得的数据。而 iPhone4、iPhone4s、iPone5 等,如果要实现记步功能,只能利用加速传感器跟算法配合来实现了。
下面仅讨论在机器有协处理器的情况下,如何利用系统提供的记步 API。
#####iOS7
在 iOS7 中,可以利用 CMStepCounter
(deprecated in iOS8)。初始化:
1 2 3 4 5 6 7 8 9 10 11 12 13
| - (CMStepCounter *)stepCounter { if (![CMStepCounter isStepCountingAvailable]) { NSLog(@"计步器 CMStepCounter 不可用"); return nil; } if (!_stepCounter) { _stepCounter = [[CMStepCounter alloc] init]; } return _stepCounter; }
|
开始记步:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| - (void)startStepCounting { NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [self.stepCounter startStepCountingUpdatesToQueue:queue updateOn:1 withHandler:^(NSInteger numberOfSteps, NSDate * _Nonnull timestamp, NSError * _Nullable error) { if (error) { NSLog(@"计步 CMStepCounter 错误:%@", error); return; } dispatch_async(dispatch_get_main_queue(), ^{ self.countLabel.text = [NSString stringWithFormat:@"%ld", (long)numberOfSteps]; }); }]; }
|
#####iOS8
在 iOS8 中,使用类 CMPedometer
。初始化:
1 2 3 4 5 6 7 8 9 10 11 12 13
| - (CMPedometer *)pedometer { if (![CMPedometer isStepCountingAvailable]) { NSLog(@"计步器 CMPedometer 不可用"); return nil; } if (!_pedometer) { _pedometer = [[CMPedometer alloc] init]; } return _pedometer; }
|
开始记步:
1 2 3 4 5 6 7 8 9 10 11 12
| - (void)startStepCounting { [self.pedometer startPedometerUpdatesFromDate:[NSDate dateWithTimeIntervalSinceNow:0] withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) { if (error) { NSLog(@"计步 CMPedometer 错误:%@", error); } dispatch_async(dispatch_get_main_queue(), ^{ self.countLabel.text = [NSString stringWithFormat:@"%@", pedometerData.numberOfSteps]; }); }]; }
|
以上
Author:
Gowen
Permalink:
http://pandara.xyz/2015/10/26/ios_pedometer/
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE
Slogan:
Do you believe in DESTINY?