读取用户步数

现在很多App都会有获取用户步数的功能,比如微信,爱奇艺、淘宝等。那么如果要获取用户步数,就要用到苹果等HealthKit。Demo

HealthKit是Apple公司在iOS 8系统中推出的,HealthKit不能再iPad中使用,而且它也不支持扩展。下面就讲一下怎么利用HealthKit获取步数。


image.png

image.png
读取权限 :
Privacy - Health Share Usage Description 
写入权限:
Privacy - Health Update Usage Description 

读取用户步数的核心代码

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end

ViewController.m

#import <HealthKit/HealthKit.h>
@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<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.healthLabel.text = [NSString stringWithFormat:@"%d",allStepCount];
        }];
    }];
    //执行查询
    [self.healthStore executeQuery:sampleQuery];
}
@end
lADPBY0V4wKWZQPNBTbNAu4_750_1334.jpg_620x10000q90g.jpg

补充

身体测量

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 日光反应型皮肤类型
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容