本来以为以后可以好好种树的,结果发现添加的数据可以在健康里面看到,但是无法在支付宝这些里面获取。。。

1,Xcode 8之后需要在info.plist 中设置以下两个权限;

(1)Privacy - Health Update Usage Description

(2)Privacy - Health Share Usage Description

2,导入头文件;

#import <HealthKit/HealthKit.h>
#import <UIKit/UIDevice.h>

3,设置读取数据的权限和写入数据的权限

#pragma mark - 设置写入权限
- (NSSet *)dataTypesToWrite {
    HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    HKQuantityType *distanceType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
    return [NSSet setWithObjects:stepType,distanceType, nil];
}

#pragma mark - 设置读取权限
- (NSSet *)dataTypesToRead {

以下为设置的权限类型:

HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    HKQuantityType *distanceType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];

return [NSSet setWithObjects:stepType,distanceType, nil];
}

以下是关于fitness的全部权限介绍可以直接去看HKQuantityType.h文件很详细,有//fitness,// Body Measurements,// Results,// Vitals等

// Fitness
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierStepCount HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0);                 // Scalar(Count),               Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceWalkingRunning HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0);    // Length,                      Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceCycling HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0);           // Length,                      Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceWheelchair HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0);       // Length,               Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierBasalEnergyBurned HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0);         // Energy,                      Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierActiveEnergyBurned HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0);        // Energy,                      Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierFlightsClimbed HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0);            // Scalar(Count),               Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierNikeFuel HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0);                  // Scalar(Count),               Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierAppleExerciseTime HK_AVAILABLE_IOS_WATCHOS(9_3, 2_2);         // Time                         Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierPushCount HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0);                // Scalar(Count),               Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceSwimming HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0);         // Length,                      Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierSwimmingStrokeCount HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0);      // Scalar(Count),               Cumulative

4,判断设备是否支持

if(![HKHealthStore isHealthDataAvailable]){
        NSLog(@"设备不支持healthkit");
    }

5,获取权限和获取数据

//    此处获取权限的写入和读取 获取之后才可以加到数据中
    NSSet *writeDataTypes = [self dataTypesToWrite];
    NSSet *readDataTypes = [self dataTypesToRead];
    [self.healthstore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError * _Nullable error) {
        if (success) {
 
            [self getStepsFromHealthKit];//第二种获取方法
//            [self getdistanceFromHealthKit]; //获取公里数
        }else{
       
        }
    }];
    
6,获取具体的数据的方法,三个方法是一起的//unit此处需要注意的是单位的不同

- (void)getDistancesFromHealthKit{
    HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
    [self fetchSumOfSamplesTodayForType:stepType unit:[HKUnit meterUnit] completion:^(double stepCount, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"你的公里数为:%.f",stepCount);
            self.pedoLab.text = [NSString stringWithFormat:@"%.2fm",stepCount];
        });
    }];
}

#pragma mark - 读取HealthKit数据
- (void)fetchSumOfSamplesTodayForType:(HKQuantityType *)quantityType unit:(HKUnit *)unit completion:(void (^)(double, NSError *))completionHandler {
    NSPredicate *predicate = [self predicateForSamplesToday];
    
    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
        HKQuantity *sum = [result sumQuantity];
        NSLog(@"result ==== %@",result);
        if (completionHandler) {
            double value = [sum doubleValueForUnit:unit];
             NSLog(@"sum ==== %@",sum);
            NSLog(@"value ===%f",value);

completionHandler(value, error);
        }
    }];
    [self.healthstore executeQuery:query];
}

#pragma mark - NSPredicate数据模型
- (NSPredicate *)predicateForSamplesToday {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *now = [NSDate date];
    NSDate *startDate = [calendar startOfDayForDate:now];
    NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
    return [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
}

7,添加和写入数据,并重新获取数据

#pragma mark - 添加步数
- (void)adddistanceWithStepNum:(double)stepNum {
    HKQuantitySample *stepCorrelationItem = [self distanceCorrelationWithStepNum:stepNum];
    
    [self.healthstore saveObject:stepCorrelationItem withCompletion:^(BOOL success, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                [self.view endEditing:YES];
                UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [doneAlertView show];
                //刷新数据  重新获取距离
                [self getDistancesFromHealthKit];
                
            }else {
                NSLog(@"The error was: %@.", error);
                UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [doneAlertView show];
                return ;
            }
        });
    }];
}

- (HKQuantitySample *)distanceCorrelationWithStepNum:(double)stepNum {
    NSDate *endDate = [NSDate date];
    NSDate *startDate = [NSDate dateWithTimeInterval:-300 sinceDate:endDate];
  /**

//这里的quantityWithUnit单位如果不对则会报错注意 ,有以下单位获取下面的对应的健康数据需要注意

+ (instancetype)meterUnitWithMetricPrefix:(HKMetricPrefix)prefix;      // m
+ (instancetype)meterUnit;  // m
+ (instancetype)inchUnit;   // in
+ (instancetype)footUnit;   // ft
+ (instancetype)yardUnit HK_AVAILABLE_IOS_WATCHOS(9_0, 2_0);   // yd
+ (instancetype)mileUnit;   // mi

**/
    HKQuantity *stepQuantityConsumed = [HKQuantity quantityWithUnit:[HKUnit meterUnit] doubleValue:stepNum];
    HKQuantityType *stepConsumedType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
    
    NSString *strName = [[UIDevice currentDevice] name];
    NSString *strModel = [[UIDevice currentDevice] model];
    NSString *strSysVersion = [[UIDevice currentDevice] systemVersion];
    NSString *localeIdentifier = [[NSLocale currentLocale] localeIdentifier];
    
    HKDevice *device = [[HKDevice alloc] initWithName:strName manufacturer:@"Apple" model:strModel hardwareVersion:strModel firmwareVersion:strModel softwareVersion:strSysVersion localIdentifier:localeIdentifier UDIDeviceIdentifier:localeIdentifier];
    
   // HKQuantitySample *stepConsumedSample = [HKQuantitySample quantitySampleWithType:stepConsumedType quantity:stepQuantityConsumed startDate:startDate endDate:endDate device:device metadata:nil];

//此处在iOS 8 的系统中使用会崩溃,报错找不到该方法,由于以前一直用iOS10的系统测试的未曾发现这个问题,修改为以下方法即可

HKQuantitySample *stepConsumedSample = [HKQuantitySample quantitySampleWithType:stepConsumedType quantity:stepQuantityConsumed startDate:startDate endDate:endDate];

return stepConsumedSample;
}

十,iOS 健康数据获取权限和写入权限相关推荐

  1. linux文件访问权限,Linux文件权限和访问模式

    为了更加安全的存储文件,Linux为不同的文件赋予了不同的权限,每个文件都拥有下面三种权限: 所有者权限:文件所有者能够进行的操作 组权限:文件所属用户组能够进行的操作 外部权限(其他权限):其他用户 ...

  2. 服务器怎么设置网站写入权限,如何设置服务器写入权限设置方法

    如何设置服务器写入权限设置方法 内容精选 换一换 将用户组添加至企业项目中,并为其设置一定的权限策略,该用户组中的用户即可拥有策略定义的对该企业项目中资源的使用权限.本小节指导您如何为企业项目添加用户 ...

  3. 生产中NFS案例记录---写入权限解决过程

        生产中NFS案例记录---写入权限解决过程 NFS配置要求: 1. 将oracle文件写入到NFS Server端,注意权限要与oracle端一致. 2. Oracle端目录文件所属用户为or ...

  4. 对服务器文件夹写,服务器文件夹写入权限设置

    服务器文件夹写入权限设置 内容精选 换一换 Linux x86-64(64位)服务器,常见的有EulerOS.Ubuntu.Debian.CentOS.OpenSUSE等.Windows 7及以上版本 ...

  5. iOS相册、相机、通讯录权限获取

    iOS相册.相机.通讯录权限获取 说明 这是本人写的一个工具,用以便利的处理各种权限获取的操作,目前提供相册.照相机.通讯录的权限获取操作,参考了 http://www.jianshu.com/p/a ...

  6. 在Winform程序中设置管理员权限及为用户组添加写入权限

    在我们一些Winform程序中,往往需要具有一些特殊的权限才能操作系统文件,我们可以设置运行程序具有管理员权限或者设置运行程序的目录具有写入的权限,如果是在操作系统里面,我们可以设置运行程序以管理员身 ...

  7. linux chattr 无权限,从零开始学习Linux(二十八):文件权限之chattr权限

    1.chattr命令 命令格式: chattr [+-=] [选项] 文件名或者目录名: 参数说明: +:增加权限: -:删除权限: = 等于某权限: 选项说明: i:如果对文件设置i属性,则不允许对 ...

  8. 安装VS2010旗帜版,出现“某些组件必须安装在 目录下,请检查是否有足够的写入权限以及足够的空间”

    安装VS2010旗帜版时,我用的安装文件是一个ISO文件,用虚拟光驱加载的,但是在安装时却出现了错误:"某些组件必须安装在 目录下,请检查是否有足够的写入权限以及足够的空间"?这可 ...

  9. 如果Python对于磁盘没有写入权限,还会运行吗?

    Python如果对于磁盘没有写入权限,那么编译成功的字节码文件就只会存储在内存当中,而不会写入到磁盘,每次运行Python都会重新编译,然后运行. 转载于:https://www.cnblogs.co ...

最新文章

  1. 怎么遍历服务器文件夹,遍历远程服务器某个文件夹下的文件
  2. 程序员最痛苦的事,就是程序出错;程序员最最痛苦的事,就是程序出错了还没有错误信息!--IIS Service Unavailable 问题如何解决...
  3. php和python的多线程,Python多线程以及线程锁简单理解(代码)
  4. 计算机在输电线路设计中的应用研究,计算机在输电线路基础设计中的应用原稿(备份存档)...
  5. Java并发编程-ReentrantLock
  6. DG SG childSG fatherSG
  7. 电脑快捷键(键盘不灵了赶紧使用快捷键)
  8. 在iOS开发中,我们会遇到十六进制和字符串之间相互转换,话不多说,直接上代码:...
  9. php创建文件目录,及删除目录和文件
  10. 在线教育直播平台对比(钉钉/保利威/小鹅通)
  11. 如何选择合适的地图注记手段
  12. 强网杯2022 crypto 复现
  13. MyBatisPlus 查询selectOne方法
  14. CAN总线简易入门教程
  15. 最新 iOS13 苹果登录
  16. python输入n个数、输出最小的数字_程序查找最少的斐波纳契数以在Python中加到n?...
  17. 很不错的正则表达式前端使用手册
  18. CC00047.bdpositions——|Hadoop实时数仓.V27|——|项目.v27|需求三:数据处理增量统计广告.V1|——|需求分析|
  19. 获取当前登录用户的IP地址代码
  20. 博文第二天,一切刚刚开始

热门文章

  1. 产业互联网时代的到来(内容摘自看雪论坛)
  2. 阿里云ddns,动态域名更新Python脚本,基于Python3,适用于linux
  3. [转载] 将kg/m^2转化为mm的理解
  4. R语言RStan贝叶斯示例:重复试验模型和种群竞争模型Lotka Volterra
  5. EMNLP22评测矩阵:FineD-Eval: Fine-grained Automatic Dialogue-Level Evaluation
  6. python按列索引提取文件夹内所有excel指定列汇总
  7. Virtualbox安装增强功能时显示【未能加载虚拟光盘】
  8. 情感障碍学计算机好吗,AI系统怎么帮助双相情感障碍患者
  9. 关于Fluent网格尺寸的疑惑
  10. 你睡得那么晚,一定是程序员吧