Objective-C修改运动步数

iOS上面的计步应用都是访问“健康”内的数据,所以只要修改“健康”的数据就可以达到修改QQ或者微信步数的需求,装X神技。
首先打开HealthKit:TARGETS–Capabilities–HealthKit
Objective-C修改运动步数_第1张图片
然后倒入导入HealthKit.framework:TARGETS–Build Phases–Link Binary With Libraries
Objective-C修改运动步数_第2张图片
导入头文件:

#import 

主要的代码:

//获取权限
        HKQuantityType *stepCountType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        NSSet *writeDataTypes = [NSSet setWithObjects:stepCountType, nil];
        [self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:nil completion:^(BOOL success, NSError * _Nullable error) {
        }];
        //修改步数
        HKQuantityType * quantityTypeIdentifier = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
        HKQuantity *quantity = [HKQuantity quantityWithUnit:[HKUnit countUnit] doubleValue:stepsCounts];
        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(), ^{
                    [self _showAlert:@"添加成功"];
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self _showAlert:@"添加失败"];
                });
            }
        }];

stepsCounts为要修改的步数,需要注意的是:要回到主线程来进行UI操作,显示Alert,而且需要真机运行。
GitHub上demo地址:https://github.com/FEverStar/ChangeStepCounts.git

你可能感兴趣的:(iOS开发,iOS开发入门到精通)