美文网首页
iOS通过HealthKit来修改步数(添加)

iOS通过HealthKit来修改步数(添加)

作者: Smallwolf_JS | 来源:发表于2018-09-17 17:05 被阅读278次

    最近微信的步数排名,支付宝的步数,QQ的步数霸占首页等等,好像很火的样子!

    • 首先你需要你的App支持healthkit,如下图


    • 并且要在plist设置访问权限的提示语句
      Privacy - Health Update Usage Descriptionapp需要访问你的健康数据

    • 在你的代码中引入
      #import <HealthKit/HealthKit.h>
      添加一个属性,并初始化
      @property (nonatomic,strong) HKHealthStore *healthStore;

    - (HKHealthStore *)healthStore{
        if (!_healthStore) {
            _healthStore = [[HKHealthStore alloc]init];
        }
        return _healthStore;
    }
    
    • 具体执行的代码
    //获取权限
        HKQuantityType *stepCountType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        NSSet *writeDataTypes = [NSSet setWithObjects:stepCountType, nil];
        [self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:nil completion:^(BOOL success, NSError * _Nullable error) {
            
            if (success) {
                //修改步数
                HKQuantityType * quantityTypeIdentifier = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
                HKQuantity *quantity = [HKQuantity quantityWithUnit:[HKUnit countUnit] doubleValue:30000.0f];
                HKQuantitySample *temperatureSample = [HKQuantitySample quantitySampleWithType:quantityTypeIdentifier quantity:quantity startDate:[NSDate date] endDate:[NSDate date] metadata:nil];
                
                [self.healthStore saveObject:temperatureSample withCompletion:^(BOOL success, NSError * _Nullable error) {
                    if (success) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"添加成功");
                        });
                    }else{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"添加失败");
                        });
                    }
                }];
            }
        }];
    

    然后你就可以在你的健康应用里面查看添加的步数了


    希望我的代码可以帮助到大家。

    相关文章

      网友评论

          本文标题:iOS通过HealthKit来修改步数(添加)

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