您的位置:首页 > 移动开发 > Objective-C

Objective-C修改运动步数

2016-09-28 10:23 197 查看
iOS上面的计步应用都是访问“健康”内的数据,所以只要修改“健康”的数据就可以达到修改QQ或者微信步数的需求,装X神技。

首先打开HealthKit:TARGETS–Capabilities–HealthKit



然后倒入导入HealthKit.framework:TARGETS–Build Phases–Link Binary With Libraries



导入头文件:

#import <HealthKit/HealthKit.h>


主要的代码:

//获取权限
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 步数 HealthKit