这篇文章是搬迁自我的新浪博客,因为无法自动搬迁所以就自己动手了
关于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;
}