iOS 健康 获取运动步数 距离 时间
1 把HeathKit打开
2 申请权限 包含读和写的 支持iOS8以上 5s及以上
引入头文件
#import <HealthKit/HealthKit.h>
#import <UIKit/UIDevice.h>
#define HKVersion [[[UIDevice currentDevice] systemVersion] doubleValue]
#define CustomHealthErrorDomain @"com.sdqt.healthError"
3 申请权限
@property (nonatomic, strong) HKHealthStore *healthStore;
[self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {if (compltion != nil) {NSLog(@"error->%@", error.localizedDescription);compltion (success, error);}}];
4 读和写权限
/*!* @brief 写权限* @return 集合*/
- (NSSet *)dataTypesToWrite
{HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];HKQuantityType *temperatureType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature];HKQuantityType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];return [NSSet setWithObjects:heightType, temperatureType, weightType,activeEnergyType,nil];
}/*!* @brief 读权限* @return 集合*/
- (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];return [NSSet setWithObjects:heightType, temperatureType,birthdayType,sexType,weightType,stepCountType, distance, activeEnergyType,nil];
}
5 获取运动步数和时长
//获取步数
- (void)getStepCount:(void(^)(double value, NSError *error))completion{//HKQuantityTypeIdentifierStepCount 计算步数HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];//排序规则NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];//HKObjectQueryNoLimit 数量限制HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:stepType predicate:[HealthKitManage predicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {if(error){completion(0,error);}else{NSInteger totleSteps = 0;double sumTime = 0;//获取数组for(HKQuantitySample *quantitySample in results){HKQuantity *quantity = quantitySample.quantity;HKUnit *heightUnit = [HKUnit countUnit];double usersHeight = [quantity doubleValueForUnit:heightUnit];NSLog(@"%f",usersHeight);totleSteps += usersHeight;NSDateFormatter *fm=[[NSDateFormatter alloc]init];fm.dateFormat=@"yyyy-MM-dd HH:mm:ss";NSString *strNeedStart = [fm stringFromDate:quantitySample.startDate];NSLog(@"startDate %@",strNeedStart);NSString *strNeedEnd = [fm stringFromDate:quantitySample.endDate];NSLog(@"endDate %@",strNeedEnd);sumTime += [quantitySample.endDate timeIntervalSinceDate:quantitySample.startDate];}NSLog(@"当天行走步数 = %ld",(long)totleSteps);int h = sumTime / 3600;int m = ((long)sumTime % 3600)/60;NSLog(@"运动时长:%@小时%@分", @(h), @(m));completion(totleSteps,error);}}];[self.healthStore executeQuery:query];
}
6 公里数和步数相似
//获取公里数
- (void)getDistance:(void(^)(double value, NSError *error))completion
{HKQuantityType *distanceType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:distanceType predicate:[HealthKitManage predicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {if(error){completion(0,error);}else{double totleSteps = 0;for(HKQuantitySample *quantitySample in results){HKQuantity *quantity = quantitySample.quantity;HKUnit *distanceUnit = [HKUnit meterUnitWithMetricPrefix:HKMetricPrefixKilo];double usersHeight = [quantity doubleValueForUnit:distanceUnit];totleSteps += usersHeight;}NSLog(@"当天行走距离 = %.2f",totleSteps);completion(totleSteps,error);}}];[self.healthStore executeQuery:query];
}/*!* @brief 当天时间段** @return 时间段*/
+ (NSPredicate *)predicateForSamplesToday {//获取日历NSCalendar *calendar = [NSCalendar currentCalendar];//获取当前时间NSDate *now = [NSDate date];NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:now];//设置为0[components setHour:0];[components setMinute:0];[components setSecond:0];//设为开始时间NSDate *startDate = [calendar dateFromComponents:components];//把开始时间之后推一天为结束时间NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];//设置开始时间和结束时间为一段时间NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];return predicate;
}
6 获取数据
HealthKitManage *manage = [HealthKitManage shareInstance];[manage authorizeHealthKit:^(BOOL success, NSError *error) {if (success) {NSLog(@"success");[manage getStepCount:^(double value, NSError *error) {NSLog(@"1count-->%.0f", value);NSLog(@"1error-->%@", error.localizedDescription);dispatch_async(dispatch_get_main_queue(), ^{stepLabel.text = [NSString stringWithFormat:@"步数:%.0f步", value];});}];}else {NSLog(@"fail");}}];
HealthKitManage *manage = [HealthKitManage shareInstance];[manage authorizeHealthKit:^(BOOL success, NSError *error) {if (success) {NSLog(@"success");[manage getDistance:^(double value, NSError *error) {NSLog(@"2count-->%.2f", value);NSLog(@"2error-->%@", error.localizedDescription);dispatch_async(dispatch_get_main_queue(), ^{distanceLabel.text = [NSString stringWithFormat:@"公里数:%.2f公里", value];});}];}else {NSLog(@"fail");}}];
Demo
http://download.csdn.net/detail/rpf2014/9862258
iOS 健康 获取运动步数 距离 时间相关推荐
- android读取运动数据权限_各种手机使用金管家平安Run健康行运动步数上传不计步读取时怎么解决?...
最近很多平安用户在使用平安各种App时,App里面的运动步数记步活动就算参加了,步数要么不显示.要么显示为零.要么跟手机自带运动记步器显示有不一样的差别,这些都是跟手机本身设置有关系,接下来淘小爱就讲 ...
- 小程序获取运动步数php,微信小程序怎么获取php页面数据?
如何获取微信小程序用户openid onLaunch: function(){ var that = this var user=wx.getStorageSync('user') || {}; va ...
- iOS-获取健康运动步数
iOS获取健康的运动步数,需要注意筛选下用户手动编辑录入的数据,HKMetadataKeyWasUserEntered 为1时,为手动录入数据. 获取健康运动数据前,需要在该key下添加HealhtK ...
- 69、Android获取每日运动步数
安卓获取步数 - areful - 博客园 https://www.jianshu.com/p/cfc2a200e46d android获取当前步数 - 王怀宇 - 博客园TodayStepCount ...
- Android获取不到运动步数(踩坑)
Android获取不到运动步数(踩坑) 获取运动步数 某些手机获取不到步数 获取运动步数 使用SensorManager,也就是手机内置的传感器获取运动步数,通过该方法可获取到当前运动步数.开机后总运 ...
- 微信小程序获取用户运动步数后端返回-41003
最近在做一个运动步数兑换的小程序,记录下自己遇到的一些问题:1.授权流程(需要获取用户信息的授权和获取运动步数的授权)2.在获取运动步数时后端一直返回-41003 一.授权流程 由于微信的一些授权接口 ...
- iOS 使用HealthKit框架实现获取今日步数
Demo地址:我的github仓库 HealthKit hey!宝宝又来更新博客了! 今天早上查看天气,发现自己缺少一个查看天气的APP, 于是下载了一个"墨迹天气",结果宝宝在欣 ...
- iOS 获取手机步数
在iphone设备中我们应该如何的去获取用户所走的步数,其实大概可以有三种方式 1.利用HealthKit框架从健康App中去获取步数,缺点 2.可以利用废弃的CMStepCounter 3.利用 C ...
- 获取this_小程序获取微信运动步数并集成echarts报表显示
需求 现在运动计步非常的火,大家常用的计步工具一般有keep.咕咚.微信运动和其他移动设备等,本文是基于微信小程序获取用户的微信运动数据并可视化呈现出来. 先看一下最终实现效果: 微信运动规则 在开发 ...
最新文章
- WMI技术介绍和应用——查询驱动信息
- 阿里云服务器上使用iptables设置安全策略
- 计算机视野仪检测青光眼的操作,计算机视野仪检测青光眼的操作及体会
- 第四范式“金融范”系列分享会第二期开课:人工智能强化金融风控
- 游戏的社交与延伸:怎样把玩家连结起来?
- 浅析NameNode/DataNode/SecondaryNameNode源码注释
- SQL Server2008 用编写脚本自动生成的Sql语言出现 “列名显示无效 ”错误
- 【Arthas】Arthas 类查找和反编译原理
- HttpClient 实现爬取百度搜索结果(自动翻页)
- 矩阵快速幂的学习(系统的学习)
- extends 和super 泛型限定符-上界不存下界不取
- 专用计算机数控编程软件有哪些,大家都用什么数控编程软件
- HIT CS科班对计算机专业素养的理解
- Linux编写脚本nsum求和,shell脚本学习与总结
- antd4.x [antd: Switch] `value` is not a valid prop, do you mean `checked`? 解决办法
- 获取与设置checkbox选中状态
- 搞 Java 的年薪 40W 是什么水平?
- Abaqus2019的abaqus_v6.env在哪里
- [附源码]java毕业设计校园拓展活动管理系统
- moviepy多张图片合成视频