您的位置:首页 > 移动开发 > IOS开发

iOS 计步器的实现

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

首先了解一下API:

步数计数可用性

+
isStepCountingAvailable

开始和停止更新步数计数


startStepCountingUpdatesToQueue:updateOn:withHandler:


stopStepCountingUpdates


获取历史步数计数数据


queryStepCountStartingFrom:to:toQueue:withHandler:

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

+ (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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: