最近做一个健康的项目,需要获取运动步数,睡眠时间,于是研究了一下HealthKit,下面分享一下,下来几张图:
Demo下载地址:
https://github.com/TechAlleyBoy/HealthKitDemo
http://download.csdn.net/download/techalleyboy/9867771

一:准备工作
1:在开发者账号(https://developer.apple.com)中配置AppID时需要选中HealthKit。如下图

2:在targets的capabilities中打开HealthKit。如下图

3:infoPlist需要配置权限 NSHealthUpdateUsageDescription 如下图

    <key>NSHealthShareUsageDescription</key><string>是否允许更新健康数据</string><key>NSHealthUpdateUsageDescription</key><string>是否允许分享健康数据</string>

二:创建一个健康的单例管理类HealthKitManager
1:.h文件,解释详见代码注释

/*** 健康单例*/
+ (instancetype)sharedInstance;/*** 检查是否支持获取健康数据*/
- (void)authorizeHealthKit:(void(^)(BOOL success, NSError *error))compltion;/*** 获取步数*/
- (void)getStepCount:(void(^)(NSString *stepValue, NSError *error))completion;/*** 获取睡眠*/
- (void)getSleepCount:(void(^)(NSString *sleepValue, NSError *error))completion;

2:.m文件,解释详见代码注释
注意:
1):统计步数的时间是,今天00:00:00 - 今天23:59:59
2):统计睡眠的时间是,昨天12:00:00 - 今天12:00:00

//
//  HealthKitManager.m
//  BJTResearch
//
//  Created by yunlong on 2017/6/9.
//  Copyright © 2017年 yunlong. All rights reserved.
//#import "HealthKitManager.h"
#import <HealthKit/HealthKit.h>
@interface HealthKitManager ()
//HKHealthStore类提供用于访问和存储用户健康数据的界面。
@property (nonatomic, strong) HKHealthStore *healthStore;
@end
@implementation HealthKitManager#pragma mark - 健康单例
+ (instancetype)sharedInstance {static HealthKitManager *instance;static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{instance = [[HealthKitManager alloc] init];});return instance;
}#pragma mark - 检查是否支持获取健康数据
- (void)authorizeHealthKit:(void(^)(BOOL success, NSError *error))compltion {if (![HKHealthStore isHealthDataAvailable]) {NSError *error = [NSError errorWithDomain: @"不支持健康数据" code: 2 userInfo: [NSDictionary dictionaryWithObject:@"HealthKit is not available in th is Device"                                                                      forKey:NSLocalizedDescriptionKey]];if (compltion != nil) {compltion(NO, error);}return;}else{if(self.healthStore == nil){self.healthStore = [[HKHealthStore alloc] init];}//组装需要读写的数据类型NSSet *writeDataTypes = [self dataTypesToWrite];NSSet *readDataTypes = [self dataTypesRead];//注册需要读写的数据类型,也可以在“健康”APP中重新修改[self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {if (compltion != nil) {NSLog(@"error->%@", error.localizedDescription);compltion (YES, error);}}];}
}#pragma mark - 写权限
- (NSSet *)dataTypesToWrite{//步数HKQuantityType *stepCountType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];//身高HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];//体重HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];//活动能量HKQuantityType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];//体温HKQuantityType *temperatureType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature];//睡眠分析HKCategoryType *sleepAnalysisType = [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];return [NSSet setWithObjects:stepCountType,heightType, temperatureType, weightType,activeEnergyType,sleepAnalysisType,nil];
}#pragma mark - 读权限
- (NSSet *)dataTypesRead{//身高HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];//体重HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];//体温HKQuantityType *temperatureType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature];//出生日期HKCharacteristicType *birthdayType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth];//性别HKCharacteristicType *sexType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex];//步数HKQuantityType *stepCountType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];//步数+跑步距离HKQuantityType *distance = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];//活动能量HKQuantityType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];//睡眠分析HKCategoryType *sleepAnalysisType = [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];return [NSSet setWithObjects:heightType, temperatureType,birthdayType,sexType,weightType,stepCountType, distance, activeEnergyType,sleepAnalysisType,nil];
}#pragma mark - 获取步数
- (void)getStepCount:(void(^)(NSString *stepValue, NSError *error))completion{//要检索的数据类型。HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];//NSSortDescriptors用来告诉healthStore怎么样将结果排序。NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];/*@param         sampleType      要检索的数据类型。@param         predicate       数据应该匹配的基准。@param         limit           返回的最大数据条数@param         sortDescriptors 数据的排序描述@param         resultsHandler  结束后返回结果*/HKSampleQuery*query = [[HKSampleQuery alloc] initWithSampleType:stepType predicate:[HealthKitManager getStepPredicateForSample] limit:HKObjectQueryNoLimit sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {if(error){completion(0,error);}else{NSLog(@"resultCount = %ld result = %@",results.count,results);//把结果装换成字符串类型double totleSteps = 0;for(HKQuantitySample *quantitySample in results){HKQuantity *quantity = quantitySample.quantity;HKUnit *heightUnit = [HKUnit countUnit];double usersHeight = [quantity doubleValueForUnit:heightUnit];totleSteps += usersHeight;}NSLog(@"最新步数:%ld",(long)totleSteps);completion([NSString stringWithFormat:@"%ld",(long)totleSteps],error);}}];[self.healthStore executeQuery:query];
}#pragma mark - 获取睡眠(昨天12点到今天12点)
- (void)getSleepCount:(void(^)(NSString *sleepValue, NSError *error))completion{//要检索的数据类型。HKSampleType *sleepType = [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:false];HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:sleepType predicate:[HealthKitManager getSleepPredicateForSample] limit:HKObjectQueryNoLimit sortDescriptors:@[sortDescriptor] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {if (error) {NSLog(@"=======%@", error.domain);}else{NSLog(@"resultCount = %ld result = %@",results.count,results);NSInteger totleSleep = 0;for (HKCategorySample *sample in results) {//0:卧床时间 1:睡眠时间  2:清醒状态NSLog(@"=======%@=======%ld",sample, sample.value);if (sample.value == 1) {NSTimeInterval i = [sample.endDate timeIntervalSinceDate:sample.startDate];totleSleep += i;}}NSLog(@"睡眠分析:%.2f",totleSleep/3600.0);completion([NSString stringWithFormat:@"%.2f",totleSleep/3600.0],error);}}];[self.healthStore executeQuery:query];
}#pragma mark - 当天时间段
+ (NSPredicate *)getStepPredicateForSample {NSDate *now = [NSDate date];NSDateFormatter * formatter = [[NSDateFormatter alloc] init];[formatter setDateFormat:@"yyyyMMdd"];NSString *startFormatValue = [NSString stringWithFormat:@"%@000000",[formatter stringFromDate:now]];NSString *endFormatValue = [NSString stringWithFormat:@"%@235959",[formatter stringFromDate:now]];[formatter setDateFormat:@"yyyyMMddHHmmss"];NSDate * startDate = [formatter dateFromString:startFormatValue];NSDate * endDate = [formatter dateFromString:endFormatValue];NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];return predicate;
}#pragma mark - 昨天12点到今天12点
+ (NSPredicate *)getSleepPredicateForSample {NSDateFormatter * formatter = [[NSDateFormatter alloc] init];[formatter setDateFormat:@"yyyyMMdd"];//今天12点NSDate *now = [NSDate date];NSString *endFormatValue = [NSString stringWithFormat:@"%@120000",[formatter stringFromDate:now]];//昨天12点NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:now];//前一天NSString *startFormatValue = [NSString stringWithFormat:@"%@120000",[formatter stringFromDate:lastDay]];[formatter setDateFormat:@"yyyyMMddHHmmss"];NSDate * startDate = [formatter dateFromString:startFormatValue];NSDate * endDate = [formatter dateFromString:endFormatValue];NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];return predicate;
}@end

三:控制器UIViewController中调用HealthKitManager

#import "ViewController.h"
#import "HealthKitManager.h"
@interface ViewController ()
//步数
@property(nonatomic,strong) UILabel *stepLabel;//睡眠
@property(nonatomic,strong) UILabel *sleepLabel;
@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.self.view.backgroundColor = [UIColor whiteColor];UIButton *stepBtn = [UIButton buttonWithType:UIButtonTypeCustom];stepBtn.frame = CGRectMake(50, 100, 50, 40);[stepBtn setTitle:@"步数" forState:UIControlStateNormal];[stepBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];stepBtn.backgroundColor = [UIColor redColor];[self.view addSubview:stepBtn];[stepBtn addTarget:self action:@selector(stepBtnClick) forControlEvents:UIControlEventTouchUpInside];_stepLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, 100, 200, 40)];_stepLabel.backgroundColor = [UIColor greenColor];_stepLabel.textAlignment = NSTextAlignmentCenter;_stepLabel.textColor = [UIColor blackColor];[self.view addSubview:_stepLabel];UIButton *sleepBtn = [UIButton buttonWithType:UIButtonTypeCustom];sleepBtn.frame = CGRectMake(50, 150, 50, 40);[sleepBtn setTitle:@"睡眠" forState:UIControlStateNormal];[sleepBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];sleepBtn.backgroundColor = [UIColor redColor];[self.view addSubview:sleepBtn];[sleepBtn addTarget:self action:@selector(sleepBtnClick) forControlEvents:UIControlEventTouchUpInside];_sleepLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, 150, 200, 40)];_sleepLabel.backgroundColor = [UIColor greenColor];_sleepLabel.textAlignment = NSTextAlignmentCenter;_sleepLabel.textColor = [UIColor blackColor];[self.view addSubview:_sleepLabel];
}#pragma mark - 获取步数
- (void)stepBtnClick{[[HealthKitManager sharedInstance] authorizeHealthKit:^(BOOL success, NSError *error) {if (success) {[[HealthKitManager sharedInstance] getStepCount:^(NSString *stepValue, NSError *error) {dispatch_async(dispatch_get_main_queue(), ^{_stepLabel.text = [NSString stringWithFormat:@"步数:%@步", stepValue];});}];}else{NSLog(@"=======%@", error.domain);}}];
}#pragma mark - 获取睡眠
- (void)sleepBtnClick{[[HealthKitManager sharedInstance] authorizeHealthKit:^(BOOL success, NSError *error) {if (success) {[[HealthKitManager sharedInstance] getSleepCount:^(NSString *sleepValue, NSError *error) {dispatch_async(dispatch_get_main_queue(), ^{_sleepLabel.text = [NSString stringWithFormat:@"睡眠:%@小时", sleepValue];});}];}}];
}

如果觉得我的文章对您有用,请顶一下。您的支持将鼓励我继续创作!

iOS利用HealthKit获取健康里的步数和睡眠时间相关推荐

  1. iOS利用HealthKit框架从健康app中获取步数信息

    微信和QQ的每日步数最近十分火爆,我就想为自己写的项目中添加一个显示每日步数的功能,上网一搜好像并有相关的详细资料,自己动手丰衣足食. 统计步数信息并不需要我们自己去实现,iOS自带的健康app已经为 ...

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

    Demo地址:我的github仓库 HealthKit hey!宝宝又来更新博客了! 今天早上查看天气,发现自己缺少一个查看天气的APP, 于是下载了一个"墨迹天气",结果宝宝在欣 ...

  3. php 动态多维数组长度,怎么在php中利用count获取多维数组的长度

    怎么在php中利用count获取多维数组的长度 发布时间:2021-01-05 16:38:55 来源:亿速云 阅读:80 作者:Leah 今天就跟大家聊聊有关怎么在php中利用count获取多维数组 ...

  4. iOS获取健康步数从加速计到healthkit

    转自:http://www.cnblogs.com/dongliu/p/5629065.html 计步模块接触了一年多,最近又改需求了,所以又换了全新的统计步数的方法,整理一下吧. 在iPhone5s ...

  5. HealthKit 从健康app中获取步数信息

    原文:http://blog.csdn.net/dynastyting/article/details/51858595 微信和QQ的每日步数最近十分火爆,我就想为自己写的项目中添加一个显示每日步数的 ...

  6. uni-app利用uniCloud获取微信步数并将数据写入数据库

    uni-app利用uniCloud获取微信步数并将数据写入数据库 本项目依赖了uni-id 只是毕业设计,想法不完善,没有对用户授权失败做处理,如果编写的时候需要注意 第一步:调用wx.login() ...

  7. iOS - 苹果健康架构 基于HealthKit的健康数据的编辑

    最近公司需求,研究了一周之久的苹果健康架构,内容包括:资料调研.报告与HealthKit.framework - API,这一研习还在持续进行中.至此,主要认识到了2点:对苹果健康健康架构设计与实现原 ...

  8. 乐心健康php,在线刷乐心健康微信支付宝步数模板

    源码说明 在线刷乐心健康微信支付宝步数模板,用的是之前开源的接口源码稍作改动,使用Cookie存了账号密码省的每次都要输入,接口请求参数是用iOS手机重新抓包的乐心健康,和php版本的请求参数稍微不同 ...

  9. ios使用KeyChain获取唯一不变的udid

    本文是iOS7系列文章第一篇文章,主要介绍使用KeyChain保存和获取APP数据,解决iOS7上获取不变UDID的问题.并给出一个获取UDID的工具类,使用方便,只需要替换两个地方即可. 一.iOS ...

  10. vue 获取请求url_vue 获取url里参数的两种方法小结

    我就废话不多说了,大家还是直接看代码吧~ 第一种: const query = Qs.parse(location.search.substring(1)) let passport = query. ...

最新文章

  1. RHEL 6上KVM的安装配置及使用-将物理接口桥接到桥接器
  2. python安装后pip用不了 cmd命令窗口提示:Did not provide a command
  3. 页面与页面之间传递参数
  4. AtomicLong和LongAdder的区别
  5. 内存泄漏(OOM)产生原因
  6. bzoj 1293: [SCOI2009]生日礼物
  7. android listview局部刷新和模拟应用下载
  8. ci.php教程,CodeIgniter
  9. 创龙SOM-TL437xF 核心板简介(二)
  10. win7激活成功 但每次开机后又显示此windows副本不是正版的解决办法
  11. GSWiFi校园网路由器设置方法最新版
  12. 特种浓缩分离:染料纳滤膜脱盐浓缩技术
  13. android字符串末尾添加,android在textview编辑的末尾追加''
  14. kali linux手机版下载免root,不需要root在安卓完全安装metasploit
  15. JavaEE学习08(解决项目导入eclipse后项目中的红错号)
  16. 【千锋】网络安全学习笔记(三)
  17. Django框架初体验(二)
  18. 2kids学汉字 android,2Kids学汉字
  19. linux live cd下载地址,Finnix 120 发布下载,基于Debian的Linux Live CD
  20. mysql sdo geometry_Oracle 关于WKT构造SDO_GEOMETRY的问题。详解

热门文章

  1. 各品牌智能电视刷机怎么寻找对应固件包?详细图文教程分享
  2. java 最新手机号校验
  3. linux内核的学习方法
  4. 爱心函数可视化 python
  5. stats | 广义线性模型(一)——广义线性模型的基本结构及与线性模型的比较...
  6. ol xyz 加载天地图_OpenLayers 3 之 加载天地图
  7. Java文件上传同时携带参数
  8. Python批量复制文件夹(以及所有子文件夹)下的某类型文件
  9. java计算机毕业设计房产中介管理系统源码+系统+lw+数据库+调试运行
  10. 如何制作WIFI二维码,实现手机扫一扫快速连接