iOS之healthKit
requestAuthorizationToShareTypes:readTypes:completion:
方法来请求获取HealthKit数据的权限。对每种类型的数据,你都必须请求许可来共享和读取。
SignedData ::= SEQUENCE { version CMSVersion, digestAlgorithms DigestAlgorithmIdentifiers, encapContentInfo EncasulatedContentInfo, signerInfos SignerInfo }
SignerInfo ::= SEQUENCE { version CMSVersion, sid SignerIdentifier, digestAlgorithm DigestAlgorithmIdentifier, signatureAlgorithem SignatureAlgorithmIdentifier, signatureSignatureValue }
#import <UIKit/UIKit.h>
#import <HealthKit/HealthKit.h>///健康的头文件
@interface ViewController : UIViewController
@property (nonatomic,strong)HKHealthStore *healthStore;
@end
//===========获取步数
#import "ViewController.h"
@interface ViewController ()
@property (strong,nonatomic) UILabel *StepsLable;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
UILabel *StepsLable=[[UILabelalloc]initWithFrame:CGRectMake(30, 100, 200, 50)];
self.StepsLable=StepsLable;
[self.viewaddSubview:StepsLable];
// 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;
NSTimer *timer=[NSTimerscheduledTimerWithTimeInterval:1target:selfselector:@selector(timerrepeat)userInfo:nilrepeats:YES];
[[NSRunLoopcurrentRunLoop]addTimer:timerforMode:NSRunLoopCommonModes];
}
-(void)timerrepeat{
NSLog(@"定时器执行");
[selfgetAuthority];
}
#pragma mark 获取权限
- (void)getAuthority
{
//查看healthKit在设备上是否可用,iPad上不支持HealthKit
if (![HKHealthStoreisHealthDataAvailable]) {
self.StepsLable.text = @"该设备不支持HealthKit";
}
//创建healthStore对象
self.healthStore = [[HKHealthStorealloc]init];
//设置需要获取的权限类型这里仅设置了步数
HKObjectType *stepType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet *healthSet = [NSSetsetWithObjects:stepType,nil];//权限集合
//从健康应用中获取权限
[self.healthStorerequestAuthorizationToShareTypes:nilreadTypes:healthSet completion:^(BOOL success,NSError * _Nullable error) {
if (success) {
//获取步数后我们调用获取步数的方法
[selfreadStepCount];
}
else
{
self.StepsLable.text =@"获取步数权限失败";
}
}];
}
#pragma mark 读取步数查询数据
- (void)readStepCount
{
//查询采样信息
HKSampleType *sampleType = [HKQuantityTypequantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
//NSSortDescriptor来告诉healthStore怎么样将结果排序
NSSortDescriptor *start = [NSSortDescriptorsortDescriptorWithKey:HKSampleSortIdentifierStartDateascending:NO];
NSSortDescriptor *end = [NSSortDescriptorsortDescriptorWithKey:HKSampleSortIdentifierEndDateascending:NO];
//获取当前时间
NSDate *now = [NSDatedate];
NSCalendar *calender = [NSCalendarcurrentCalendar];
NSUInteger unitFlags =NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *dateComponent = [calendercomponents:unitFlags fromDate:now];
int hour = (int)[dateComponenthour];
int minute = (int)[dateComponentminute];
int second = (int)[dateComponentsecond];
NSDate *nowDay = [NSDatedateWithTimeIntervalSinceNow: - (hour*3600 + minute * 60 + second) ];
//时间结果与想象中不同是因为它显示的是0区
// NSLog(@"今天%@",nowDay);
NSDate *nextDay = [NSDatedateWithTimeIntervalSinceNow: - (hour*3600 + minute * 60 + second) + 86400];
// NSLog(@"明天%@",nextDay);
NSPredicate *predicate = [HKQuerypredicateForSamplesWithStartDate:nowDayendDate:nextDay options:(HKQueryOptionNone)];//谓词过滤,这里过滤的是今天的数据
/*查询的基类是HKQuery,这是一个抽象类,能够实现每一种查询目标,这里我们需要查询的步数是一个HKSample类所以对应的查询类是HKSampleQuery(继承与HKQuery)。下面的limit参数传1表示查询最近一条数据,查询多条数据只要设置limit的参数值(无论什么值)就可以了*/
HKSampleQuery *sampleQuery = [[HKSampleQueryalloc]initWithSampleType:sampleTypepredicate:predicate limit:0 sortDescriptors:@[start,end]resultsHandler:^(HKSampleQuery *_Nonnull query,NSArray<__kindofHKSample *> * _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 = [stepStrcomponentsSeparatedByString:@" "][0];
int stepNum = [strintValue];
// NSLog(@"%d",stepNum);
//把一天中所有时间段中的步数加到一起
allStepCount = allStepCount + stepNum;
}
NSLog(@"--总步数-----%d",allStepCount);
//查询要放在多线程中进行,如果要对UI进行刷新,要回到主线程
[[NSOperationQueuemainQueue]addOperationWithBlock:^{
self.StepsLable.text = [NSStringstringWithFormat:@"%d",allStepCount];
}];
}];
//执行查询
[self.healthStoreexecuteQuery:sampleQuery];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
===========方法二++++++
-(void)testone{
//创建healthStore实例对象
self.healthStore = [[HKHealthStore alloc] init];
//设置需要获取的权限这里仅设置了步数
HKObjectType *stepCount = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet *healthSet = [NSSet setWithObjects:stepCount, nil];
//从健康应用中获取权限
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
if (success)
{
NSDateFormatter *formatter = [[NSDateFormatter alloc ]init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *now = [NSDate date];
NSString *todaystr = [formatter stringFromDate:now];
NSDate *today = [formatter dateFromString:todaystr];
NSDate *next = [today dateByAddingTimeInterval:24*60*60];
//定义需要获取的数据为步数
HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
//设置获取的步数时间间隔
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = 1;
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:today endDate:next options:HKQueryOptionStrictStartDate];
NSString *deviceName=@"lambo";
//创建查询统计对象collectionQuery
HKStatisticsCollectionQuery *collectionQuery = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options: HKStatisticsOptionCumulativeSum | HKStatisticsOptionSeparateBySource anchorDate:[NSDate dateWithTimeIntervalSince1970:0] intervalComponents:dateComponents];
collectionQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection * __nullable result, NSError * __nullable error) {
int numberOfSteps = 0;
for (HKStatistics *statistic in result.statistics) {
for (HKSource *source in statistic.sources) {
//HKSource对象中的name可用于区分健康数据来源--deviceName----app名称
if ([source.name isEqualToString:deviceName]) {
int steps = [[statistic sumQuantityForSource:source] doubleValueForUnit:[HKUnit countUnit]];
numberOfSteps += steps;
}
//deviceName是根据接入的设备做的标记,
if ([deviceName isEqualToString:@"iPhone"]) {
if ([source.name isEqualToString:[UIDevice currentDevice].name]) {
int steps = [[statistic sumQuantityForSource:source] doubleValueForUnit:[HKUnit countUnit]];
numberOfSteps += steps;
}
}else if ([deviceName isEqualToString:@"iWatch"] && ![source.name isEqualToString:[UIDevice currentDevice].name]){
if ([source.bundleIdentifier hasPrefix:@"com.apple.health"]) {
int steps = [[statistic sumQuantityForSource:source] doubleValueForUnit:[HKUnit countUnit]];
numberOfSteps += steps;
}
}else if ([deviceName isEqualToString:@"xiaomi"]){
if ([source.name isEqualToString:@"小米运动"] || [source.bundleIdentifier isEqualToString:@"HM.wristband"]) {
int steps = [[statistic sumQuantityForSource:source] doubleValueForUnit:[HKUnit countUnit]];
numberOfSteps += steps;
}
}
}
}
NSLog(@"ff = %d",numberOfSteps);
//步数看这里就好
NSString * stepString = [NSString stringWithFormat:@"%d",numberOfSteps];
};
[self.healthStore executeQuery:collectionQuery];
}
else
{
NSLog(@"获取步数权限失败");
}
}];
}
iOS之healthKit相关推荐
- iOS 使用HealthKit框架实现获取今日步数
Demo地址:我的github仓库 HealthKit hey!宝宝又来更新博客了! 今天早上查看天气,发现自己缺少一个查看天气的APP, 于是下载了一个"墨迹天气",结果宝宝在欣 ...
- iOS利用HealthKit框架从健康app中获取步数信息
微信和QQ的每日步数最近十分火爆,我就想为自己写的项目中添加一个显示每日步数的功能,上网一搜好像并有相关的详细资料,自己动手丰衣足食. 统计步数信息并不需要我们自己去实现,iOS自带的健康app已经为 ...
- iOS开发 HealthKit初步探索
功能: 经过用户允许后,获得苹果用户的健康信息 苹果政策不允许: 虚假,错误的信息 存储信息 健康广告 需要提供隐私政策 介绍中要有接入的介绍 如果有治疗建议或者诊断,需要提供监管部门的审批 代码基本 ...
- 【转载】我的编程之路——知识管理与知识体系
[https://segmentfault.com/a/1190000004612590] 本文的资料放到了Github Repo (本文介绍的这种笔记排布方式不一定适合于初学者理解) 六年前笔者开始 ...
- iOS Healthkit 使用探索分析
一 基本认知层面: HealthKit框架提供了一个结构,应用可以使用它来分享健康和健身数据.HealthKit管理从不同来源获得的数据,并根据用户的偏好设置,自动将不同来源的所有数据合并起来.应用还 ...
- IOS审核被拒 这里您的应用使用HealthKit
IOS审核被拒 这里您的应用使用HealthKit,但您的应用似乎不包含任何需要健康或健身数据的主要功能. uniapp上架苹果商店因为运动健康问题被拒绝 解决办法 uniapp上架苹果商店因为运动健 ...
- iOS 审核被拒记录 Guideline 2.5.1 HealthKit; 2.5.4 UIBackgroundModes audio; 1.5 Developer Information
iOS 审核被拒记录 2.5.1 解决方案一(当前项目不需要HealthKit框架,将HealthKit相关内容和权限移除) 解决方案二(当前项目需要HealthKit框架) iOS 审核被拒记录 2 ...
- android计步器摘要,ios - Healthkit每小时活动摘要包含步数,距离和卡路里? - 堆栈内存溢出...
查询Healthkit应返回包含步长,距离和卡路里的数组对象. 我能够单独归还他们 活动步骤/小时 func activitySteps(_ startDate:NSDate, endDate:NSD ...
- iOS - 苹果健康架构 基于HealthKit的健康数据的编辑
最近公司需求,研究了一周之久的苹果健康架构,内容包括:资料调研.报告与HealthKit.framework - API,这一研习还在持续进行中.至此,主要认识到了2点:对苹果健康健康架构设计与实现原 ...
- iOS 审核因为HealthKit被拒的解决方式
最近公司提交项目给苹果审核时,遇到一个奇怪的错误. 如图 翻译如图 这个错误就是说在我在项目中使用了HealthKit,但是在审核过程中并没有看到任何需要健康或者健身数据的主要功能. 经过一番查找,终 ...
最新文章
- 《Android开发从零开始》——11.AbsoluteLayoutFrameLayout学习
- 服务器搭建邮件自动回复,在postfix邮件系统上搭建自动回复邮件系统
- python如何安装scrapy库_python2安装scrapy库报错解决方案
- POJ1990:MooFest——题解
- 为 hexo 博客添加本地搜索功能
- Mybatis源码研究6:元数据(metadata)
- Ubuntu 18.04 下安装pip3及pygame模块
- html 拼接onmouseout,HTML onmouseout事件用法及代码示例
- AT91RM9200Linux移植笔记(三)-移植Linux kernel 2.6.17
- C语言(CED)递归实现汉诺塔问题
- 计算机网络之数据链路层:3、差错控制(奇偶校验、CRC冗余校验、海明校验)
- mysql sql 备份数据_mysql怎么进行数据库备份和还原,以及自动备份
- m.2接口和nvme区别_M.2接口硬盘当真速度就快吗?这些不懂就别乱买!今天再说一遍...
- 360 c语言 笔试,奇虎360校招的笔试真题
- 遥感数字图像融合算法简介
- 医学知识-骨密度以及骨密度测量
- Hexo接入网易云评论
- 满纸荒唐言:Processing 寻觅文字魅力篇
- MGCtoken与IMtoken哪个好?安全吗?
- kurento服务器搭建(docker方式)
热门文章
- 我个人中意的VS2017/VS2019插件,推荐给大家(#^.^#)
- 关于BASE编码 16 32 36 58 64 58 91
- Wolfram|Alpha搜索引擎
- 关于射频同轴连接器的功率容量探讨
- vs哪个版本好用_5个版本17款白金爱他美,究竟选哪个?德国版/澳洲版/卓萃/英国.....
- 差别-request.getParameterValues与request.getParameter
- 如何批量制作ITF-14条码
- 水星网卡 linux驱动,水星网卡驱动下载_硬件驱动下载
- 数学分析教程(科大)——7.1笔记+习题
- 基于linkboy+GD32编程实现多种屏幕显示效果(LCD1602、LCD12864、彩屏)