- 导入框架:
在项目中导入
HealthKit.framework
。
#import <HealthKit/HealthKit.h>
- 检查HealthKit可用性:
if (![HKHealthStore isHealthDataAvailable]) {
// HealthKit不可用,进行相应处理
return;
}
- 创建HealthStore实例:
HKHealthStore *healthStore = [[HKHealthStore alloc] init];
- 授权访问步数数据:
- 定义要读取的数据类型,步数数据类型为
HKQuantityTypeIdentifierStepCount
。
HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet<HKObjectType *> *readTypes = [NSSet setWithObject:stepCountType];
[healthStore requestAuthorizationToShareTypes:nil readTypes:readTypes completion:^(BOOL success, NSError * _Nullable error) {
if (!success || error) {
// 授权失败处理
NSLog(@"授权失败: %@", error);
return;
}
// 授权成功,可以进行数据查询
}];
- 数据查询:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
NSDate *startDate = [calendar dateFromComponents:components];
NSDate *endDate = [NSDate date];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];
HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:stepCountType
quantitySamplePredicate:predicate
options:HKStatisticsOptionCumulativeSum
completionHandler:^(HKStatisticsQuery * _Nonnull query, HKStatistics * _Nullable result, NSError * _Nullable error) {
if (error) {
// 查询出错处理
NSLog(@"查询错误: %@", error);
return;
}
HKQuantity *totalSteps = result.sumQuantity;
if (totalSteps) {
double stepCount = [totalSteps doubleValueForUnit:[HKUnit countUnit]];
NSLog(@"今天的步数: %.0f", stepCount);
}
}];
[healthStore executeQuery:query];