iOS 计步器的实现

来源:互联网 发布:mac启动盘重装系统 编辑:程序博客网 时间:2024/06/05 12:45

在iOS 使用CMStepCounter实现计步器功能。需要注意的是:需要iPhone5S及以上型号的手机和iOS7.0及以上的操作系统

首先了解一下API:

步数计数可用性

  • + isStepCountingAvailable

开始和停止更新步数计数

  • – startStepCountingUpdatesToQueue:updateOn:withHandler:

  • – stopStepCountingUpdates

获取历史步数计数数据

  • – queryStepCountStartingFrom:to:toQueue:withHandler:

下边介绍具体的使用方法:

+ (void)getStepCounter:(void (^)(NSString * totalStep))step

{

    __blockNSInteger stepNumber = 0;

   if (![CMStepCounterisStepCountingAvailable]) {

        UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:@"警告"message:@"只支持iPhone5S及以上型号的手机"delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil];

        [alert show];

    }

    

    NSDate* nowDate = [NSDatedate];

    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];

    [dateFormatter setDateFormat:@"HH:mm:ss"];

    NSArray *stringArray = [[dateFormatterstringFromDate:nowDate] componentsSeparatedByString:@":"];

    NSTimeInterval  oneDay = [[stringArrayobjectAtIndex:0]integerValue] *3600  + [[stringArrayobjectAtIndex:1]integerValue] *60 + [[stringArrayobjectAtIndex:2]integerValue] ;

    //获取指定时间段之前

    NSDate* theDate = [nowDateinitWithTimeIntervalSinceNow: -oneDay];

    

    NSOperationQueue * operationQueue = [[NSOperationQueuealloc] init];

    CMStepCounter * stepCounter = [[CMStepCounteralloc] init];

    //获取今天的步数

    [stepCounter queryStepCountStartingFrom:theDateto:nowDate toQueue:operationQueuewithHandler:^(NSInteger numberOfSteps,NSError * _Nullable error) {

        if (error) {

            //暂时没有处理

        }

        else {

            stepNumber = numberOfSteps;

        }

    }];

    

    //开始计步

    [stepCounter startStepCountingUpdatesToQueue:operationQueueupdateOn:1withHandler:  ^(NSInteger numberOfSteps,NSDate *timestamp, NSError *error) {

        if (error) {

            //暂时没有处理

        }

        else {

            step([NSStringstringWithFormat:@"%zd", stepNumber + numberOfSteps]);

        }

    }];

}

参考文献:http://www.tuicool.com/articles/MNfu63   http://blog.csdn.net/u011010305/article/details/48932235
0 0