现在很多App都会有获取用户步数的功能,比如微信,爱奇艺、淘宝等。那么如果要获取用户步数,就要用到苹果等HealthKit。Demo
HealthKit是Apple公司在iOS 8系统中推出的,HealthKit不能再iPad中使用,而且它也不支持扩展。下面就讲一下怎么利用HealthKit获取步数。
读取权限 :
Privacy - Health Share Usage Description
写入权限:
Privacy - Health Update Usage Description
读取用户步数的核心代码
ViewController.h
#import
@interface ViewController : UIViewController
@end
ViewController.m
#import
@interface ViewController ()
@property (nonatomic,strong) HKHealthStore *healthStore;
@property (weak, nonatomic) IBOutlet UILabel *healthLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)healthButton:(id)sender {
//查看healthKit在设备上是否可用,iPad上不支持HealthKit
if (![HKHealthStore isHealthDataAvailable]) {
self.healthLabel.text = @"NO";
}
//创建healthStore对象
self.healthStore = [HKHealthStore new];
//设置需要获取的权限,这里仅设置了步数
HKObjectType *steptpye = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet *healtSet = [NSSet setWithObjects:steptpye, nil];
//从健康应用中获取权限
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:healtSet completion:^(BOOL success, NSError * _Nullable error) {
if (success) {
//获取步数后我们调用获取步数的方法
[self readStepCount];
}else{
self.healthLabel.text = @"NO";
}
}];
}
#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 *new = [NSDate date];
NSCalendar *calender = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *dateComponent = [calender components:unitFlags fromDate:new];
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
补充
身体测量
1. HKQuantityTypeIdentifierBodyMassIndex 身高体重指数
2. HKQuantityTypeIdentifierBodyFatPercentage 体脂率
3. HKQuantityTypeIdentifierHeight 身高
4. HKQuantityTypeIdentifierBodyMass 体重
5. HKQuantityTypeIdentifierLeanBodyMass 去脂体重
健身数据
1. HKQuantityTypeIdentifierStepCount 步数
2. HKQuantityTypeIdentifierDistanceWalkingRunning 步行+跑步距离
3. HKQuantityTypeIdentifierDistanceCycling 骑车距离
4.HKQuantityTypeIdentifierDistanceWheelchair 轮椅距离
5. HKQuantityTypeIdentifierBasalEnergyBurned 静息能量
6. HKQuantityTypeIdentifierActiveEnergyBurned 活动能量
7. HKQuantityTypeIdentifierFlightsClimbed 已爬楼层
8. HKQuantityTypeIdentifierNikeFuel NikeFuel
9. HKQuantityTypeIdentifierAppleExerciseTime 锻炼分钟数健身数据
10.HKQuantityTypeIdentifierDistanceSwimming 游泳距离
11.HKQuantityTypeIdentifierSwimmingStrokeCount 游泳冲刺次数
主要特征
1. HKQuantityTypeIdentifierHeartRate 心率
2. HKQuantityTypeIdentifierBodyTemperature 体温
3. HKQuantityTypeIdentifierBasalBodyTemperature 基础体温
4. HKQuantityTypeIdentifierBloodPressureSystolic 收缩压
5. HKQuantityTypeIdentifierBloodPressureDiastolic 舒张压
6. HKQuantityTypeIdentifierRespiratoryRate 呼吸速率
数据结果
1. HKQuantityTypeIdentifierOxygenSaturation 血氧饱和度
2. HKQuantityTypeIdentifierPeripheralPerfusionIndex 末梢灌注指数
3. HKQuantityTypeIdentifierBloodGlucose 血糖
4. HKQuantityTypeIdentifierNumberOfTimesFallen 摔倒次数
5. HKQuantityTypeIdentifierElectrodermalActivity 皮电活动
6. HKQuantityTypeIdentifierInhalerUsage 吸入剂用量
7. HKQuantityTypeIdentifierBloodAlcoholContent 血液酒精浓度
8. HKQuantityTypeIdentifierForcedVitalCapacity 最大肺活量|用力肺活量
9. HKQuantityTypeIdentifierForcedExpiratoryVolume1 第一秒用力呼气量
10.HKQuantityTypeIdentifierPeakExpiratoryFlowRate 呼气流量峰值
营养摄入
1. HKQuantityTypeIdentifierDietaryFatTotal 总脂肪
2. HKQuantityTypeIdentifierDietaryFatPolyunsaturated 多元不饱和脂肪
3. HKQuantityTypeIdentifierDietaryFatMonounsaturated 单元不饱和脂肪
4. HKQuantityTypeIdentifierDietaryFatSaturated 饱和脂肪
5. HKQuantityTypeIdentifierDietaryCholesterol 膳食胆固醇
6. HKQuantityTypeIdentifierDietarySodium 钠
7. HKQuantityTypeIdentifierDietaryCarbohydrates 碳水化合物
8. HKQuantityTypeIdentifierDietaryFiber 纤维
9. HKQuantityTypeIdentifierDietarySugar 膳食糖
10.HKQuantityTypeIdentifierDietaryEnergyConsumed 膳食能量
11.HKQuantityTypeIdentifierDietaryProtein 蛋白质
12.HKQuantityTypeIdentifierDietaryVitaminA 维生素 A
13.HKQuantityTypeIdentifierDietaryVitaminB6 维生素 B6
14.HKQuantityTypeIdentifierDietaryVitaminB12 维生素 B12
15.HKQuantityTypeIdentifierDietaryVitaminC 维生素 C
16.HKQuantityTypeIdentifierDietaryVitaminD 维生素 D
17.HKQuantityTypeIdentifierDietaryVitaminE 维生素 E
18.HKQuantityTypeIdentifierDietaryVitaminK 维生素 K
19.HKQuantityTypeIdentifierDietaryCalcium 钙
20.HKQuantityTypeIdentifierDietaryIron 铁
21.HKQuantityTypeIdentifierDietaryThiamin 硫铵
22.HKQuantityTypeIdentifierDietaryRiboflavin 核黄素
23.HKQuantityTypeIdentifierDietaryNiacin 烟酸
24.HKQuantityTypeIdentifierDietaryFolate 叶酸
25.HKQuantityTypeIdentifierDietaryBiotin 生物素
26.HKQuantityTypeIdentifierDietaryPantothenicAcid 泛酸
27.HKQuantityTypeIdentifierDietaryPhosphorus 磷
28.HKQuantityTypeIdentifierDietaryIodine 碘
29.HKQuantityTypeIdentifierDietaryMagnesium 镁
30.HKQuantityTypeIdentifierDietaryZinc 锌
31.HKQuantityTypeIdentifierDietarySelenium 硒
32.HKQuantityTypeIdentifierDietaryCopper 铜
33.HKQuantityTypeIdentifierDietaryManganese 锰
34.HKQuantityTypeIdentifierDietaryChromium 铬
35.HKQuantityTypeIdentifierDietaryMolybdenum 钼
36.HKQuantityTypeIdentifierDietaryChloride 氯化物
37.HKQuantityTypeIdentifierDietaryPotassium 钾
38.HKQuantityTypeIdentifierDietaryCaffeine 咖啡因
39.HKQuantityTypeIdentifierDietaryWater 水
40.HKQuantityTypeIdentifierUVExposure 紫外线指数
生殖健康
1. HKCategoryTypeIdentifierSleepAnalysis 睡眠分析
2.HKCategoryTypeIdentifierAppleStandHour 站立小时
3. HKCategoryTypeIdentifierCervicalMucusQuality 宫颈粘液质量
4. HKCategoryTypeIdentifierOvulationTestResult 排卵测试结果
5. HKCategoryTypeIdentifierMenstrualFlow 月经
6. HKCategoryTypeIdentifierIntermenstrualBleeding 点滴出血
7. HKCategoryTypeIdentifierSexualActivity 性行为
8.HKCategoryTypeIdentifierMindfulSession 正念分钟数
本人信息
1. HKCharacteristicTypeIdentifierBiologicalSex 性别
2. HKCharacteristicTypeIdentifierBloodType 血型
3. HKCharacteristicTypeIdentifierDateOfBirth 出生日期
4. HKCharacteristicTypeIdentifierFitzpatrickSkinType 日光反应型皮肤类型