HealthKit读写步数

环境:Xcode7.3、iPhone6s Plus(iOS 9.3.1)
iOS8以上真机调试
证书需要打开获取健康数据功能
Apple官方Demo

读数据时区分手机自动计算步数和App写入的步数

需要导入 #import <HealthKit/HealthKit.h>

定义显示

@property (nonatomic, weak) IBOutlet UILabel *stepCountUnitLabel;
@property (nonatomic, weak) IBOutlet UILabel *stepCountValueLabel;

使用

- (void)viewDidAppear:(BOOL)animated 
{
    [super viewDidAppear:animated];

    // Set up an HKHealthStore, asking the user for read/write permissions. The profile view controller is the
    // first view controller that's shown to the user, so we'll ask for all of the desired HealthKit permissions now.
    // In your own app, you should consider requesting permissions the first time a user wants to interact with
    // HealthKit data.
    if ([HKHealthStore isHealthDataAvailable]) {
        NSSet *writeDataTypes = [self dataTypesToWrite];
        NSSet *readDataTypes = [self dataTypesToRead];
        
        [self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {
            if (!success) {
                NSLog(@"You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: %@. If you're using a simulator, try it on a device.", error);
                
                return;
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                [self updateStepCountLabel];
            });
        }];
    }
}

#pragma mark - HealthKit Permissions

// Returns the types of data that Fit wishes to write to HealthKit.
// 写入数据
- (NSSet *)dataTypesToWrite 
{
    HKQuantityType *dietaryCalorieEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryEnergyConsumed]; // 膳食能量
    HKQuantityType *activeEnergyBurnType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned]; // 活动能量
    HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight]; // 身高
    HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass]; // 体重
    
    HKQuantityType *stepCountType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; // 步数
    
    return [NSSet setWithObjects:dietaryCalorieEnergyType, activeEnergyBurnType, heightType, weightType, stepCountType, nil];
}

// Returns the types of data that Fit wishes to read from HealthKit.
// 读取数据
- (NSSet *)dataTypesToRead 
{
    HKQuantityType *dietaryCalorieEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDietaryEnergyConsumed]; // 膳食能量
    HKQuantityType *activeEnergyBurnType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned]; // 活动能量
    HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight]; // 身高
    HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass]; // 体重
    HKCharacteristicType *birthdayType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth]; // 出生日期
    HKCharacteristicType *biologicalSexType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex]; // 性别
    
    HKQuantityType *stepCountType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; // 步数
    
    return [NSSet setWithObjects:dietaryCalorieEnergyType, activeEnergyBurnType, heightType, weightType, birthdayType, biologicalSexType, stepCountType, nil];
}

读取步数数据

- (void)updateStepCountLabel
{
    self.stepCountUnitLabel.text = @"步数 (健康+App步)";
    self.stepCountValueLabel.text = @"0";
    
    HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    //NSSortDescriptors用来告诉healthStore怎么样将结果排序。
    NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
    NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    // 当天时间段
    NSPredicate *todayPredicate = [self predicateForSamplesToday];
    HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:stepCountType predicate:todayPredicate limit:HKObjectQueryNoLimit sortDescriptors:@[start, end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
        //打印查询结果
        NSLog(@"resultCount = %ld result = %@",results.count,results);
        double deviceStepCounts = 0.f;
        double appStepCounts = 0.f;
        for (HKQuantitySample *result in results) {
            HKQuantity *quantity = result.quantity;
            HKUnit *stepCount = [HKUnit countUnit];
            double count = [quantity doubleValueForUnit:stepCount];
            // 实例数据
//            "50 count \"Fit\" (1) 2016-07-11 17:43:03 +0800 2016-07-11 17:43:03 +0800",
//            "26 count \"你的设备名\" (9.3.1) \"iPhone\" 2016-07-11 15:19:33 +0800 2016-07-11 15:19:41 +0800",

//            26:result.quantity
//            count:单位,还有其它kg、m等,不同单位使用不同HKUnit
//            \"Fit\":result.source.name
//            (9.3.1):result.device.softwareVersion,App写入的时候是空的
//            \"iPhone\":result.device.model
//            2016-07-11 15:19:33 +0800:result.startDate 
//            2016-07-11 15:19:41 +0800:result.endDate
            

            // 区分手机自动计算步数和App写入的步数
            if ([result.source.name isEqualToString:[UIDevice currentDevice].name]) {
                // App写入的数据result.device.name为空
                if (result.device.name.length > 0) {
                    deviceStepCounts += count;
                }
                else {
                    appStepCounts += count;
                }
            }
            else {
                appStepCounts += count;
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *deviceStepCountsString = [NSNumberFormatter localizedStringFromNumber:@(deviceStepCounts) numberStyle:NSNumberFormatterNoStyle];
            NSString *stepCountsString = [NSNumberFormatter localizedStringFromNumber:@(appStepCounts) numberStyle:NSNumberFormatterNoStyle];
            NSString *totalCountsString = [NSNumberFormatter localizedStringFromNumber:@(deviceStepCounts+appStepCounts) numberStyle:NSNumberFormatterNoStyle];
            
            NSString *text = [NSString stringWithFormat:@"%@+%@=%@", deviceStepCountsString, stepCountsString, totalCountsString];
            self.stepCountValueLabel.text = text;
        });
        
    }];
    //执行查询
    [self.healthStore executeQuery:sampleQuery];
}

// 当天时间段
- (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];
}

写入步数数据


- (void)saveStepCountIntoHealthStore:(double)stepCount 
{
    // Save the user's step count into HealthKit.
    HKUnit *countUnit = [HKUnit countUnit];
    HKQuantity *countUnitQuantity = [HKQuantity quantityWithUnit:countUnit doubleValue:stepCount];
    
    HKQuantityType *countUnitType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    NSDate *now = [NSDate date];
    
    HKQuantitySample *stepCountSample = [HKQuantitySample quantitySampleWithType:countUnitType quantity:countUnitQuantity startDate:now endDate:now];
    
    [self.healthStore saveObject:stepCountSample withCompletion:^(BOOL success, NSError *error) {
        if (!success) {
            NSLog(@"An error occured saving the step count sample %@. In your app, try to handle this gracefully. The error was: %@.", stepCountSample, error);
            abort();
        }
        
        [self updateStepCountLabel];
    }];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这篇文章介绍两种可以获取计步数据的方法,一种是采用CMPedometer获取手机计步器数据,另一种是采用Healt...
    丨n水瓶座菜虫灬阅读 6,079评论 5 10
  • 前几天写一个关于养生和医疗的一个项目,要写一个类似微信运动的计步器功能,只好先去研究一下计步器功能实现。 之前在我...
    小李童学阅读 2,702评论 6 8
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,262评论 4 61
  • 时间,永远按照她自己的方式,固执地去走自己的路,从不会因为别人的欢喜而凝固,亦不会因为他人的伤悲而冻结。是时间太无...
    木榴莲阅读 682评论 2 3
  • 大部分人会知道自己的英语不好有一个原因是不敢说!但他们不知道的是自己英语不好的原因100%彻彻底底就是因为不敢说!...
    海涛教练阅读 277评论 0 1