在iOS 使用CMStepCounter實現計步器功能。需要注意的是:需要iPhone5S及以上型號的手機和iOS7.0及以上的操作系統
首先了解一下API:
步數計數可用性
開始和停止更新步數計數
獲取歷史步數計數數據
下邊介紹具體的使用方法:
+ (void)getStepCounter:(void (^)(NSString * totalStep))step
{
__block NSInteger stepNumber = 0;
if (![CMStepCounter isStepCountingAvailable]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"只支持iPhone5S及以上型號的手機"delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil];
[alert show];
}
NSDate* nowDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSArray *stringArray = [[dateFormatter stringFromDate:nowDate] componentsSeparatedByString:@":"];
NSTimeInterval oneDay = [[stringArray objectAtIndex:0] integerValue] *3600 + [[stringArray objectAtIndex:1] integerValue] *60 + [[stringArray objectAtIndex:2] integerValue] ;
//獲取指定時間段之前
NSDate* theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay];
NSOperationQueue * operationQueue = [[NSOperationQueue alloc] init];
CMStepCounter * stepCounter = [[CMStepCounter alloc] init];
//獲取今天的步數
[stepCounter queryStepCountStartingFrom:theDate to:nowDate toQueue:operationQueue withHandler:^(NSInteger numberOfSteps, NSError * _Nullable error) {
if (error) {
//暫時沒有處理
}
else {
stepNumber = numberOfSteps;
}
}];
//開始計步
[stepCounter startStepCountingUpdatesToQueue:operationQueue updateOn:1 withHandler: ^(NSInteger numberOfSteps, NSDate *timestamp, NSError *error) {
if (error) {
//暫時沒有處理
}
else {
step([NSString stringWithFormat:@"%zd", stepNumber + numberOfSteps]);
}
}];
}
參考文獻:http://www.tuicool.com/articles/MNfu63 http://blog.csdn.net/u011010305/article/details/48932235