美文网首页good
[iOS]HealthKit数据读写

[iOS]HealthKit数据读写

作者: 溜萝卜 | 来源:发表于2016-10-18 15:47 被阅读1132次

    HealthManager.h

    #import <Foundation/Foundation.h>
    #import <HealthKit/HealthKit.h>
    #import <UIKit/UIDevice.h>
    
    @interface HealthManager : NSObject
    @property (nonatomic,strong) HKHealthStore *healthStore; //健康信息
    
    +(id)shareInstance;
    
    @end
    

    HealthManager.m

    //系统版本
    #define HKVersion [[[UIDevice currentDevice] systemVersion] doubleValue]
    
    • 简单的单例、写得不是很严谨
    +(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];
    
    //    HKQuantityTypeIdentifierStepCount 步数
    //    HKQuantityTypeIdentifierDistanceCycling 骑车距离
    //    HKQuantityTypeIdentifierActiveEnergyBurned 活动能量
    //    HKQuantityTypeIdentifierDistanceWalkingRunning 步行+跑步距离
        
        
            return [NSSet setWithObjects:activeEnergyType,stepCountType,cycleType,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) {
                        XLog(@"%@\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) {
                        XLog(@"health = %@",result);
                        HKQuantity *sum = [result sumQuantity];
                        
                        double value = [sum doubleValueForUnit:[HKUnit kilocalorieUnit]];
                        XLog(@"%@卡路里 ---> %.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) {
                    
                    XLog(@"Successfully saved objects to health kit");
                    
                } else {
                    
                    XLog(@"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) {
                    
                    XLog(@"Successfully saved objects to health kit");
                    
                } else {
                    
                    XLog(@"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) {
                    
                    XLog(@"Successfully saved objects to health kit");
                    
                } else {
                    
                    XLog(@"Error: %@ %@", error, [error userInfo]);
                    
                }
                
            });
            
        }];
        
        
    }
    

    还有心率的没放上去。因为我没有iwatch...QAQ, 欢迎关注我的新浪微博 微博

    相关文章

      网友评论

        本文标题:[iOS]HealthKit数据读写

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