十,iOS 健康数据获取权限和写入权限

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



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;
}


 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS和安卓的沙盒是用来保护应用程序数据的安全性的一种机制。它们的主要区别如下: 1. 安全性:iOS的沙盒机制相对安卓更加严格。iOS要求应用程序在自己的沙盒内运行,限制了应用之间的直接访问和交互。而安卓的沙盒机制相对较弱,应用程序可以更容易地访问和共享数据。 2. 文件系统结构:iOS的沙盒机制将每个应用程序的文件分隔为多个目录,包括应用程序包、文档目录、缓存目录等。每个目录只能由特定的应用程序进行访问和写入。而安卓的沙盒机制通常是基于应用的用户ID,并且应用程序可以自由地向沙盒中的文件系统写入和访问。 3. 权限管理:iOS的沙盒机制通过权限管理来限制应用程序对系统资源的访问。应用程序需要在安装时声明所需的访问权限,并由用户在使用时授予。而安卓的沙盒机制在应用程序安装时会一次性获取所有权限,并且用户只能在软件设置中进行修改。 4. 应用程序的更新:iOS的沙盒机制要求每个应用程序都在单独的容器中运行,因此应用程序的更新通常是通过替换整个应用程序包来完成的。而安卓的沙盒机制允许应用程序在更新时只替换其中的部分文件,从而减少下载和更新时间。 综上所述,iOS和安卓的沙盒机制在安全性、文件系统结构、权限管理和应用程序更新方面存在一些差异。iOS的沙盒机制相对更严格,保护了应用程序和用户数据的安全性,但也可能限制了应用程序之间的交互。而安卓的沙盒机制相对较弱,允许应用程序更自由地访问和共享数据,但也可能增加了安全隐患。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值