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

iOS 使用HealthKit框架实现获取今日步数

2016-07-08 15:29 417 查看
Demo地址:我的github仓库

HealthKit

hey!宝宝又来更新博客了!

今天早上查看天气,发现自己缺少一个查看天气的APP,

于是下载了一个“墨迹天气”,结果宝宝在欣赏这个产品的时候发现它竟然能够读取宝宝的步数!!!



不要嫌弃宝宝的步数少···但这个发现让我对这个小功能产生了无限的好奇···

于是查找iOS这方面的资料,在某篇博客里发现原来是HealthKit框架,于是对此进行研究。

觉得比较好的博客地址:HealthKit框架参考

我参考的博客地址:点击打开链接iOS利用HealthKit框架从健康app中获取步数信息

我学习的论坛地址:healthkit如何获取每天行走的步数?? 求大神解答

微信和QQ的每日步数最近十分火爆,我就想为自己写的项目中添加一个显示每日步数的功能,上网一搜好像并有相关的详细资料,自己动手丰衣足食。
统计步数信息并不需要我们自己去实现,iOS自带的健康app已经为我们统计好了步数数据。
我们只要使用HealthKit框架从健康app中获取这个数据信息就可以了。
对HealthKit框架有了简单的了解后我们就可以开始了。

1.如下图所示 在Xcode中打开HealthKit功能



2.在需要的地方#import <HealthKit/HealthKit.h>(这里我为了方便直接在viewController写了所有代码,我也在学习这个框架,个人感觉把获取数据权限的代码放在AppDelegate中更好)
获取步数分为两步1.获得权限  2.读取步数 
3.StoryBoard设计



4.代码部分
ViewController.h

#import <UIKit/UIKit.h>
#import <HealthKit/HealthKit.h>
@interface ViewController : UIViewController
@property (nonatomic,strong) HKHealthStore *healthStore;
@end
ViewController.m

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *StepsLable;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.StepsLable.layer.cornerRadius = self.StepsLable.frame.size.width/2;
self.StepsLable.layer.borderColor = [UIColor redColor].CGColor;
self.StepsLable.layer.borderWidth = 5;
self.StepsLable.layer.masksToBounds = YES;
}
#pragma mark 获取权限
- (IBAction)getAuthority:(id)sender
{
//查看healthKit在设备上是否可用,iPad上不支持HealthKit
if (![HKHealthStore isHealthDataAvailable]) {
self.StepsLable.text = @"该设备不支持HealthKit";
}

//创建healthStore对象
self.healthStore = [[HKHealthStore alloc]init];
//设置需要获取的权限 这里仅设置了步数
HKObjectType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet *healthSet = [NSSet setWithObjects:stepType,nil];

//从健康应用中获取权限
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
if (success) {
//获取步数后我们调用获取步数的方法
[self readStepCount];
}
else
{
self.StepsLable.text = @"获取步数权限失败";
}
}];
}
#pragma mark 读取步数 查询数据
- (void)readStepCount
{
//查询采样信息
HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
//NSSortDescriptor来告诉healthStore怎么样将结果排序
NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
//获取当前时间
NSDate *now = [NSDate date];
NSCalendar *calender = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *dateComponent = [calender components:unitFlags fromDate:now];
int hour = (int)[dateComponent hour];
int minute = (int)[dateComponent minute];
int second = (int)[dateComponent second];
NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second) ];
//时间结果与想象中不同是因为它显示的是0区
NSLog(@"今天%@",nowDay);
NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second)  + 86400];
NSLog(@"明天%@",nextDay);
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nowDay endDate:nextDay options:(HKQueryOptionNone)];

/*查询的基类是HKQuery,这是一个抽象类,能够实现每一种查询目标,这里我们需要查询的步数是一个HKSample类所以对应的查询类是HKSampleQuery。下面的limit参数传1表示查询最近一条数据,查询多条数据只要设置limit的参数值就可以了*/

HKSampleQuery *sampleQuery = [[HKSampleQuery alloc]initWithSampleType:sampleType predicate:predicate limit:0 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
//设置一个int型变量来作为步数统计
int allStepCount = 0;
for (int i = 0; i < results.count; i ++) {
//把结果转换为字符串类型
HKQuantitySample *result = results[i];
HKQuantity *quantity = result.quantity;
NSMutableString *stepCount = (NSMutableString *)quantity;
NSString *stepStr =[ NSString stringWithFormat:@"%@",stepCount];
//获取51 count此类字符串前面的数字
NSString *str = [stepStr componentsSeparatedByString:@" "][0];
int stepNum = [str intValue];
NSLog(@"%d",stepNum);
//把一天中所有时间段中的步数加到一起
allStepCount = allStepCount + stepNum;
}

//查询要放在多线程中进行,如果要对UI进行刷新,要回到主线程
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
self.StepsLable.text = [NSString stringWithFormat:@"%d",allStepCount];
}];
}];
//执行查询
[self.healthStore executeQuery:sampleQuery];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end


5.完成效果



点击按钮之后,首先获取获得步数权限···



允许之后健康APP中就会出现你的APP



最后APP上的文字就变成了步数



与健康上数据一样



大功告成!!!

自己研究的,可能方法有点笨,希望读者予以指正,谢谢!!!
刚写完,发现简书上一篇博客比较完整:iOS开发-读取健康中的步数和步行+跑步距离

CMPedometer(2017.8.29)

github地址:计步器
今日方才知道有一个类叫CMStepCounter,当然,这已经在iOS8淘汰了,所以今天我们学习的是CMPedometer类。
CMStepCounter记录的数据并不准确,iOS 8.0下已经过期,CMPedometer返回的结果更为精准,但是有延迟性。

接下来上代码~ 在代码上之前需要在info.plist文件里申请NSMotionUsageDescription权限~千万别忘了哦~
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>

@interface ViewController ()
@property (nonatomic, retain) CMPedometer *pedoMeter;
@property (weak, nonatomic) IBOutlet UILabel *stepLabel;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
//创建CMPedometer对象
self.pedoMeter = [[CMPedometer alloc] init];
}
- (IBAction)startCountStep:(id)sender {
//判断是否可以支持获取步数
if ([CMPedometer isStepCountingAvailable]) {
//判断是否可以支持返回步行的距离
//    if ([CMPedometer isDistanceAvailable]) {
//判断是否可以支持爬楼梯的检测
//    if ([CMPedometer isFloorCountingAvailable]) {

//当你的步数有更新的时候,会触发这个方法,返回从某一时刻开始到现在所有的信息统计CMPedometerData。
//其中CMPedometerData包含步数等信息,在下面使用的时候介绍。
//值得一提的是这个方法不会实时返回结果,每次刷新数据大概一分钟左右。
[self.pedoMeter startPedometerUpdatesFromDate:[NSDate date] withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
self.stepLabel.text = [NSString stringWithFormat:@"我已经走了%@步,距离%@米",pedometerData.numberOfSteps,pedometerData.distance];
}];

} else {
NSLog(@"设备不可用");
}
}

- (IBAction)stopCountStep:(UIButton *)sender {
//停止收集计步信息
[self.pedoMeter stopPedometerUpdates];
}
- (IBAction)lastWeek:(id)sender {
//这个方法用来查询近7天内的任意时间段的CMPedometerData信息。
//这个方法是当你请求的时候才会触发

//我查询从今天0点到现在我走了多少步
NSDate *startOfToday = [[NSCalendar currentCalendar] startOfDayForDate:[NSDate date]];
[self.pedoMeter queryPedometerDataFromDate:startOfToday toDate:[NSDate dateWithTimeIntervalSinceNow:0] withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
self.stepLabel.text = [NSString stringWithFormat:@"我已经走了%@步,距离%@米",pedometerData.numberOfSteps,pedometerData.distance];
}];

}
@end


其中CMPedometerData的属性值有:
@property(readonly, nonatomic) NSDate *startDate; 开始时间

@property(readonly, nonatomic) NSDate *endDate;  结束时间
@property(readonly, nonatomic) NSNumber *numberOfSteps; 计步
@property(readonly, nonatomic, nullable) NSNumber *distance; 距离
@property(readonly, nonatomic, nullable) NSNumber *floorsAscended;上了多少台阶
@property(readonly, nonatomic, nullable) NSNumber *floorsDescended;下了多少台阶
@property(readonly, nonatomic, nullable) NSNumber *currentPace;步速 s/m
@property(readonly, nonatomic, nullable) NSNumber *currentCadence;节奏steps/s


开始计步功能,你需要走动,或者把手机移动一段距离,才会有数据展示。
最近7天按钮,我显示的是今天的步数和距离。





小心肝儿们可以试一试···哈哈哈哈···好肉麻好肉麻,因为昨天是七夕我被秀恩爱的感染了嘛哈哈哈~

CMMotionActivityManager

github地址:CMMotionActivityManager

iOS7新增了这个类来收集、存储用户的运动数据——此处的运动数据用于反映用户当前处于步行、跑步、驾驶车辆或处于静止状态。对于导航类应用而言,可通过该类获取用户当前的运动类型的改变,并根据不同的运动类型提供更精确的导航。

1、需要iOS7 或更高版本

2、需要 手机 有 协处理器   (5S 或 以后的设备 )

3、可以检查到 五种状态 ,静止,步行  ,跑步,自行车,驾车

4、每次回调结果 ,都有 本次结果准确程度的 描述   低 ,中 ,高 三个等级

5、在导航的时候可能更智能的为用户提供步行,驾车等导航。

通过这个类获取运动数据时,程序将会得到一个CMMotionActivity对象,该对象包含如下属性:
>stationary:该属性返回用户是否处于静止状态。
>walking:该属性返回用户是否正在步行。
>running:该属性返回用户是否正在跑步。
>automotive:该属性返回用户是否正在驾车。
>unknown:该属性返回用户是都处于未知运动中。
>startDate:获取该运动的开始日期。
>confidence:该属性返回该运动数据的可靠程度。

#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *timeStampLabel;
@property (nonatomic,retain) CMMotionActivityManager *motionActivityManager;
@property (nonatomic,retain) NSDateFormatter *dateFormater;
@property (weak, nonatomic) IBOutlet UILabel *currentStateLabel;
@property (weak, nonatomic) IBOutlet UILabel *confidenceLabel;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.motionActivityManager=[[CMMotionActivityManager alloc]init];
self.dateFormater = [[NSDateFormatter alloc] init];
self.dateFormater.dateFormat = @"yyyy-MM-dd HH:mm:ss";

__weak typeof (self)weakSelf = self;
[self.motionActivityManager startActivityUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMMotionActivity *activity)
{
weakSelf.timeStampLabel.text = [weakSelf.dateFormater stringFromDate:[NSDate date]];

if (activity.unknown) {
weakSelf.currentStateLabel.text = @"未知状态";
} else if (activity.walking) {
weakSelf.currentStateLabel.text = @"步行";
} else if (activity.running) {
weakSelf.currentStateLabel.text = @"跑步";
} else if (activity.automotive) {
weakSelf.currentStateLabel.text = @"驾车";
} else if (activity.stationary) {
weakSelf.currentStateLabel.text = @"静止";
}

if (activity.confidence == CMMotionActivityConfidenceLow) {
weakSelf.confidenceLabel.text = @"准确度  低";
} else if (activity.confidence == CMMotionActivityConfidenceMedium) {
weakSelf.confidenceLabel.text = @"准确度  中";
} else if (activity.confidence == CMMotionActivityConfidenceHigh) {
weakSelf.confidenceLabel.text = @"准确度  高";
}

}];
}
@end




这个也挺好玩的,我快速抖动之后显示跑步,我轻轻的抖动显示步行,可惜我没车,没法测试了,大家可以试试~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: