這篇文章是搬遷自我的新浪博客,因爲無法自動搬遷所以就自己動手了
關於ios的計步是要區分版本的,iOS7以下,iOS7,iOS8和之上是要區分的。
關於iOS8和之上是採用CMPedometer的,要先判斷是否有計步器可用:
[CMPedometerisStepCountingAvailable]
看代碼
if (IOS8) {
if ([CMPedometerisStepCountingAvailable]) { //判斷系統的計步器是否可以使用(ios8)
if (self.setpcount == nil) {
self.setpcount = [[CMPedometer alloc] init];
}
//計步的時候要開個線程 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//開始持續更新
[self.setpcountstartPedometerUpdatesFromDate:[NSDatedate] withHandler:^(CMPedometerData *pedometerData, NSError *error) {
if (error != nil) {
return;
}
NSNumber *count = pedometerData.numberOfSteps;
myStep += [count integerValue]; //步數增加了
}];
});
}
}
對於iOS7是採用CMStepCounter來計步的,:
if ([CMStepCounter isStepCountingAvailable]) { //判斷計步器是否可用(ios7)
if (_setpcount == nil) {
_stepCount = [[CMStepCounter alloc] init];
}
//要開線程
NSOperationQueue *queue = [[NSOperationQueuealloc] init];
[_stepCountstartStepCountingUpdatesToQueue:queue updateOn:1withHandler:^(NSInteger numberOfSteps, NSDate * _Nonnull timestamp, NSError * _Nullable error) {
myStep += numberOfSteps; //在這裏步數增加了
}];
}
對於iOS7以下是採用計步算法分析陀螺儀數據來統計步數的,
- (void)userCMMotionManagerCountStep {
motionManager = [[CMMotionManageralloc] init];
motionManager.showsDeviceMovementDisplay = YES;
motionManager.deviceMotionUpdateInterval = 1.0 / 60.0;
[motionManagerstartDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXTrueNorthZVertical];
px = py = pz = 0;
NSTimeInterval updateInterval = 0.05; // 每秒採樣20次
__block NSInteger stepCount = 0; // 步數
if ([motionManagerisAccelerometerAvailable] == YES) {
[motionManagersetAccelerometerUpdateInterval:updateInterval];
[motionManagerstartAccelerometerUpdatesToQueue:[NSOperationQueuecurrentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error)
{ //以下是計步算法,分析得到的數據的,有更好的算法可用,可以替換這部分代碼
float xx = accelerometerData.acceleration.x;
float yy = accelerometerData.acceleration.y;
float zz = accelerometerData.acceleration.z;
float dot = (px * xx) + (py * yy) + (pz * zz);
float a = ABS(sqrt(px * px + py * py + pz * pz));
float b = ABS(sqrt(xx * xx + yy * yy + zz * zz));
dot /= (a * b);
if (dot <= 0.82) {
if (!isSleeping) {
isSleeping = YES;
stepCount ++;
[NSTimerscheduledTimerWithTimeInterval:0.3target:selfselector:@selector(wakeUp) userInfo:nilrepeats:NO];
}
}
px = xx; py = yy; pz = zz;
}];
}else {
[ErrorSignViewshowSignText:@"傳感器不可用"andOnParentView:[UIApplicationsharedApplication].keyWindow];
}
}
- (void)wakeUp {
isSleeping = NO;
}