美文网首页iOS常用
iOS开发——关于写入数据到HealthKit

iOS开发——关于写入数据到HealthKit

作者: _RG | 来源:发表于2020-09-09 17:15 被阅读0次
    1. 创建bundleID, 在开发者中心勾选HealthKit 选项,生成描述文件

    2.点击Capability添加HealthKit功能

    截屏2020-09-09下午5.07.07.png

    3.info.plist配置NSHealthShareUsageDescriptionNSHealthUpdateUsageDescription 两个权限提示

    4.获取权限,进行数据写入和读取

    HealthManager.h代码

    #import <Foundation/Foundation.h>
    #import <HealthKit/HealthKit.h>
    #import <UIKit/UIDevice.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface HealthManager : NSObject
    
    @property (nonatomic,strong) HKHealthStore *healthStore; //健康信息
    
    +(id)shareInstance;
    
    - (void)saveCalories:(double)calories;
    
    - (void)saveStepCount:(double)stepCount;
    
    - (void)getPermissions:(void(^)(BOOL success))Handle;
    
    //去脂体重
    - (void)saveLeanBodyMass:(double)leanBodyMass;
    
    //体重
    - (void)saveBodyMass:(double)bodyMass;
    
    //体脂率
    - (void)saveBodyFatPercentage:(double)bodyFatPercentage;
    
    //身高体重指数
    - (void)saveBodyMassIndex:(double)bodyMassIndex;
    
    @end
    
    
    

    HealthManager.m代码

    #import "HealthManager.h"
    
    //系统版本
    #define HKVersion [[[UIDevice currentDevice] systemVersion] doubleValue]
    
    @implementation HealthManager
    
    +(id)shareInstance
    {
        static id manager ;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            manager = [[[self class] alloc] init];
        });
        return manager;
    }
    
    //需要读权限的集合
    - (NSSet *)dataTypesRead
    {
        //步数
        HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        HKQuantityType *walkingRunningType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
        HKQuantityType *cycleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceCycling];
        HKQuantityType *basalEnergyType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBasalEnergyBurned];
        HKQuantityType *activeEnergyType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
        HKQuantityType *flightClimb = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierFlightsClimbed];
        HKQuantityType *heartRate = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
        HKCategoryType *standHour = [HKCategoryType categoryTypeForIdentifier:HKCategoryTypeIdentifierAppleStandHour];
        HKWorkoutType *workOut = [HKWorkoutType workoutType];
        
    
         return [NSSet setWithObjects:stepCountType, walkingRunningType,cycleType,basalEnergyType,activeEnergyType,flightClimb,standHour,heartRate,workOut,nil];
    }
    
    
    //需要写权限的集合
    - (NSSet *)dataTypesToWrite
    {
    
        HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        HKQuantityType *walkingRunningType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
        HKQuantityType *cycleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceCycling];
        HKQuantityType *activeEnergyType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
        
        
        
        
          HKQuantityType *bodyMassIndexType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex];
        
          HKQuantityType *bodyFatPercentageType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyFatPercentage];
        
        HKQuantityType *heightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
        
        HKQuantityType *bodyMassType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
        
        HKQuantityType *leanBodyMassType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierLeanBodyMass];
    
        //1. HKQuantityTypeIdentifierBodyMassIndex  身高体重指数
        //2. HKQuantityTypeIdentifierBodyFatPercentage 体脂率
        //3. HKQuantityTypeIdentifierHeight 身高
        //4. HKQuantityTypeIdentifierBodyMass 体重
        //5. HKQuantityTypeIdentifierLeanBodyMass 去脂体重
        
    //    HKQuantityTypeIdentifierStepCount 步数
    //    HKQuantityTypeIdentifierDistanceCycling 骑车距离
    //    HKQuantityTypeIdentifierActiveEnergyBurned 活动能量
    //    HKQuantityTypeIdentifierDistanceWalkingRunning 步行+跑步距离
        
        
            return [NSSet setWithObjects:activeEnergyType,stepCountType,cycleType,bodyMassIndexType,bodyFatPercentageType,heightType,bodyMassType,leanBodyMassType,nil];
        
        
    }
    
    //授权
    - (void)getPermissions:(void(^)(BOOL success))Handle
    {
        if(HKVersion >= 8.0)
        {
            if ([HKHealthStore isHealthDataAvailable]) {
                
                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 (!success) {
                        NSLog(@"%@\n\n%@",error, [error userInfo]);
                        return ;
                    }
                    else
                    {
                        Handle(YES);
                    }
                }];
                
            }
        }
    }
    
    //今天凌晨到现在
    + (NSPredicate *)predicateForSamplesToday {
        if(HKVersion >= 8.0)
        {
            // 过滤条件
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSDate *now = [NSDate date];
            NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
            
            // 开始日期
            NSDate *startDate = [calendar dateFromComponents:components];
            // 结束日期
            NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
            
            NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
            
            return predicate;
        }
        else
            return nil;
    }
    
    //步行+跑步距离
    - (void)getDistance:(NSPredicate *)predicate completionHandler:(void(^)(double value, NSError *error))handler {
        
        
        if(!(HKVersion < 8.0))
        {
            [self getPermissions:^(BOOL success) {
                if(success)
                {
                    
                    
                    HKQuantityType *type = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
                    
                    HKStatisticsQuery *staticQuery = [[HKStatisticsQuery alloc] initWithQuantityType:type
                                                                             quantitySamplePredicate:predicate
                                                                                             options:HKStatisticsOptionCumulativeSum
                                                                                   completionHandler:^(HKStatisticsQuery * _Nonnull query, HKStatistics * _Nullable result, NSError * _Nullable error) {
                                                                                       //
                                                                                       HKQuantity *quantity = result.sumQuantity;
                                                                                       NSInteger stepCount = [quantity doubleValueForUnit:[HKUnit meterUnit]];
                                                                                       
                                                                                       if (handler) {
                                                                                           handler((double)stepCount,error);
                                                                                       }
                                                                                       
                                                                                   }];
                    [self.healthStore executeQuery:staticQuery];
                    
                    
                    
                }
            }];
            
            
        }
    
        
    }
    
    //读取时间段的卡路里
    - (void)getCalorieData:(NSPredicate *)predicate completionHandler:(void(^)(double value, NSError *error))handler
    {
        
        if(!(HKVersion < 8.0)){
            [self getPermissions:^(BOOL success) {
                if(success)
                {
                    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
                    HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
                        NSLog(@"health = %@",result);
                        HKQuantity *sum = [result sumQuantity];
                        
                        double value = [sum doubleValueForUnit:[HKUnit kilocalorieUnit]];
                        NSLog(@"%@卡路里 ---> %.2lf",sum,value);
                        if(handler)
                        {
                            handler(value,error);
                        }
                    }];
                    [self.healthStore executeQuery:query];
                }
            }];
        }
    }
    
    //读取时间段的步数
    - (void)getStepCount:(NSPredicate *)predicate completionHandler:(void(^)(double value, NSError *error))handler
    {
        
        if(!(HKVersion < 8.0))
        {
            [self getPermissions:^(BOOL success) {
                if(success)
                {
                    
                    
                    HKQuantityType *type = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
                    
                    HKStatisticsQuery *staticQuery = [[HKStatisticsQuery alloc] initWithQuantityType:type
                                                                             quantitySamplePredicate:predicate
                                                                                             options:HKStatisticsOptionCumulativeSum
                                                                                   completionHandler:^(HKStatisticsQuery * _Nonnull query, HKStatistics * _Nullable result, NSError * _Nullable error) {
                                                                                       //
                                                                                       HKQuantity *quantity = result.sumQuantity;
                                                                                       NSInteger stepCount = [quantity doubleValueForUnit:[HKUnit countUnit]];
                                                                                       
                                                                                       if (handler) {
                                                                                           handler((double)stepCount,error);
                                                                                       }
                                                                                       
                                                                                   }];
                    [self.healthStore executeQuery:staticQuery];
                    
                    
                    
                }
            }];
            
            
        }
    }
    
    //写入卡路里
    - (void)saveCalories:(double)calories {
        
        
        //create sample
        HKQuantityType *calorieType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
        HKQuantity *calorieQuantity = [HKQuantity quantityWithUnit:[HKUnit kilocalorieUnit] doubleValue:calories];
        
        //sample date
        NSDate *today = [NSDate date];
        
        //create sample
        HKQuantitySample *calorieSample = [HKQuantitySample quantitySampleWithType:calorieType quantity:calorieQuantity startDate:today endDate:today];
        
        //save objects to health kit
        [self.healthStore saveObject:calorieSample withCompletion:^(BOOL success, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (success) {
                    
                    NSLog(@"Successfully saved objects to health kit");
                    
                } else {
                    
                    NSLog(@"Error: %@ %@", error, [error userInfo]);
                    
                }
                
            });
            
        }];
        
        
    }
    
    //写入步数
    - (void)saveStepCount:(double)stepCount {
        
        
        //create sample
        HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        HKQuantity *stepQuantity = [HKQuantity quantityWithUnit:[HKUnit countUnit] doubleValue:stepCount];
        
        //sample date
        NSDate *today = [NSDate date];
        
        //create sample
        HKQuantitySample *stepSample = [HKQuantitySample quantitySampleWithType:stepType quantity:stepQuantity startDate:today endDate:today];
        
        //save objects to health kit
        [self.healthStore saveObject:stepSample withCompletion:^(BOOL success, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (success) {
                    
                    NSLog(@"Successfully saved objects to health kit");
                    
                } else {
                    
                    NSLog(@"Error: %@ %@", error, [error userInfo]);
                    
                }
                
            });
            
        }];
        
        
    }
    
    //保存骑车距离
    - (void)savecycleDis:(double)dis {
    
    
    //create sample
    HKQuantityType *disType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceCycling];
    HKQuantity *disQuantity = [HKQuantity quantityWithUnit:[HKUnit meterUnit] doubleValue:dis];
    
    //sample date
    NSDate *today = [NSDate date];
    
    //create sample
    
        HKQuantitySample *stepSample = [HKQuantitySample quantitySampleWithType:disType quantity:disQuantity startDate:today endDate:today];
        
        //save objects to health kit
        [self.healthStore saveObject:stepSample withCompletion:^(BOOL success, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (success) {
                    
                    NSLog(@"Successfully saved objects to health kit");
                    
                } else {
                    
                    NSLog(@"Error: %@ %@", error, [error userInfo]);
                    
                }
                
            });
            
        }];
        
        
    }
    
    
    //1. HKQuantityTypeIdentifierBodyMassIndex  身高体重指数
    //2. HKQuantityTypeIdentifierBodyFatPercentage 体脂率
    //3. HKQuantityTypeIdentifierHeight 身高
    //4. HKQuantityTypeIdentifierBodyMass 体重
    //5. HKQuantityTypeIdentifierLeanBodyMass 去脂体重
    
    //身高体重指数
    - (void)saveBodyMassIndex:(double)bodyMassIndex {
    
    //create sample
    HKQuantityType *type = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex];
    HKQuantity *quantity = [HKQuantity quantityWithUnit:[HKUnit countUnit] doubleValue:bodyMassIndex];
    
    //sample date
    NSDate *today = [NSDate date];
    
    //create sample
    
        HKQuantitySample *stepSample = [HKQuantitySample quantitySampleWithType:type quantity:quantity startDate:today endDate:today];
        
        //save objects to health kit
        [self.healthStore saveObject:stepSample withCompletion:^(BOOL success, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (success) {
                    
                    NSLog(@"Successfully saved objects to health kit");
                    
                } else {
                    
                    NSLog(@"Error: %@ %@", error, [error userInfo]);
                    
                }
                
            });
            
        }];
        
        
    }
    
    
    //体脂率
    - (void)saveBodyFatPercentage:(double)bodyFatPercentage {
    
    //create sample
    HKQuantityType *type = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyFatPercentage];
    HKQuantity *quantity = [HKQuantity quantityWithUnit:[HKUnit percentUnit] doubleValue:bodyFatPercentage];
    
    //sample date
    NSDate *today = [NSDate date];
    
    //create sample
    
        HKQuantitySample *stepSample = [HKQuantitySample quantitySampleWithType:type quantity:quantity startDate:today endDate:today];
        
        //save objects to health kit
        [self.healthStore saveObject:stepSample withCompletion:^(BOOL success, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (success) {
                    
                    NSLog(@"Successfully saved objects to health kit");
                    
                } else {
                    
                    NSLog(@"Error: %@ %@", error, [error userInfo]);
                    
                }
                
            });
            
        }];
        
        
    }
    
    //体重
    - (void)saveBodyMass:(double)bodyMass {
    
    //create sample
    HKQuantityType *type = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
    HKQuantity *quantity = [HKQuantity quantityWithUnit:[HKUnit gramUnit] doubleValue:bodyMass];
    
    //sample date
    NSDate *today = [NSDate date];
    
    //create sample
    
        HKQuantitySample *stepSample = [HKQuantitySample quantitySampleWithType:type quantity:quantity startDate:today endDate:today];
        
        //save objects to health kit
        [self.healthStore saveObject:stepSample withCompletion:^(BOOL success, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (success) {
                    
                    NSLog(@"Successfully saved objects to health kit");
                    
                } else {
                    
                    NSLog(@"Error: %@ %@", error, [error userInfo]);
                    
                }
                
            });
            
        }];
        
        
    }
    
    
    //去脂体重
    - (void)saveLeanBodyMass:(double)leanBodyMass {
    
    //create sample
    HKQuantityType *type = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierLeanBodyMass];
    HKQuantity *quantity = [HKQuantity quantityWithUnit:[HKUnit gramUnit] doubleValue:leanBodyMass];
    
    //sample date
    NSDate *today = [NSDate date];
    
    //create sample
    
        HKQuantitySample *stepSample = [HKQuantitySample quantitySampleWithType:type quantity:quantity startDate:today endDate:today];
        
        //save objects to health kit
        [self.healthStore saveObject:stepSample withCompletion:^(BOOL success, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (success) {
                    
                    NSLog(@"Successfully saved objects to health kit");
                    
                } else {
                    
                    NSLog(@"Error: %@ %@", error, [error userInfo]);
                    
                }
                
            });
            
        }];
        
        
    }
    
    
    
    @end
    
    

    关于一些指标权限的获取, 每个指标对应的单位都在注释里面有定义

    HKQuantityTypeIdentifierBodyMassIndex  身高体重指数
     HKQuantityTypeIdentifierBodyFatPercentage 体脂率
     HKQuantityTypeIdentifierHeight 身高
     HKQuantityTypeIdentifierBodyMass 体重
     HKQuantityTypeIdentifierLeanBodyMass 去脂体重
    

    下划线的部分,包含了对应的哪个分类对应的单位方法


    image.png image.png

    参考: https://www.jianshu.com/p/5775337dac84

    相关文章

      网友评论

        本文标题:iOS开发——关于写入数据到HealthKit

        本文链接:https://www.haomeiwen.com/subject/inzeektx.html