1 首先在开发者中心 添加 HealhtKit
2 在info.plist里添加授权描述,目前只用到了获取步数的权限。
** Privacy - Motion Usage Description 允许分享步数,以帮助您记录健康**
** Privacy - Health Update Usage Description 允许更新步数,以帮助您记录健康**
** Privacy - Health Share Usage Description 允许获取步数,以帮助您记录健康**
在xcode中添加
3 封装的代码 在 HealthKitManager中
//
// LoginTool.h
// cztvNewsiPhone
//
// Created by HeJF on 2023/1/12.
// Copyright © 2023 cztv. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface HealthKitManager : NSObject
+ (instancetype)shareInstance;
//授权检测
- (void)authorizateHealthKit:(void (^)(BOOL success, NSError *error))resultBlock;
//获取当天健康数据(步数)
- (void)getStepCount:(void (^)(double stepCount, NSError *error))queryResultBlock;
//获取协处理器步数
- (void)getCMPStepCount:(void(^)(double stepCount, NSError *error))completion;
@end
NS_ASSUME_NONNULL_END
//
// LoginTool.m
// cztvNewsiPhone
//
// Created by HeJF on 2023/1/12.
// Copyright © 2023 cztv. All rights reserved.
//
#import "HealthKitManager.h"
#import <UIKit/UIDevice.h>
#import <HealthKit/HealthKit.h>
#import <CoreMotion/CoreMotion.h>
#import "UIViewController+GetViewController.h"
@interface HealthKitManager ()<UIAlertViewDelegate>
/// 健康数据查询类
@property (nonatomic, strong) HKHealthStore *healthStore;
@property (nonatomic, strong) CMPedometer * pedometer; //步数协处理器类
@property (nonatomic, strong) HKObjectType *hkOType; /**< 获取的权限 */
@property (nonatomic, strong) HKSampleType *hkSType; /**< 获取采样数据类型 */
@end
@implementation HealthKitManager
#pragma mark - 初始化单例对象
static HealthKitManager *_healthManager;
+ (instancetype)shareInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (!_healthManager) {
_healthManager = [[HealthKitManager alloc]init];
}
});
return _healthManager;
}
#pragma mark - 应用授权检查
- (void)authorizateHealthKit:(void (^)(BOOL success, NSError *error))resultBlock {
if ([HKHealthStore isHealthDataAvailable]) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSSet *readObjectTypes = [NSSet setWithObjects:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount], nil];
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:readObjectTypes completion:^(BOOL success, NSError * _Nullable error) {
if (resultBlock) {
resultBlock(success,error);
}
}];
});
}
}
#pragma mark - 获取当天健康数据(步数)
- (void)getStepCount:(void (^)(double stepCount, NSError *error))queryResultBlock {
MJWeakSelf;
HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKStatisticsQuery *query = [[HKStatisticsQuery alloc]initWithQuantityType:quantityType quantitySamplePredicate:[self predicateForSamplesToday] options:HKStatisticsOptionCumulativeSum completionHandler:^(HKStatisticsQuery * _Nonnull query, HKStatistics * _Nullable result, NSError * _Nullable error) {
if (error) {
[weakSelf getCMPStepCount: queryResultBlock];
} else {
//这里的步数是总步数,包含手动录入的,所以要有下面的方法计算出手动录入的再次减去手动录入的
double stepCount = [result.sumQuantity doubleValueForUnit:[HKUnit countUnit]];
weakSelf.hkSType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSortDescriptor *startSortDec = [NSSortDescriptor sortDescriptorWithKey:HKPredicateKeyPathStartDate ascending:NO];
NSSortDescriptor *endSortDec = [NSSortDescriptor sortDescriptorWithKey:HKPredicateKeyPathEndDate ascending:NO];
HKSampleQuery *hkSQ = [[HKSampleQuery alloc] initWithSampleType:weakSelf.hkSType
predicate:[weakSelf predicateForSamplesToday]
limit:HKObjectQueryNoLimit
sortDescriptors:@[startSortDec,endSortDec]
resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
// NSLog(@"stepCounts:%@ ---- results:%@ --- error:%@\n", query, results, error);
HKUnit *unit = [HKUnit unitFromString:@"count"];// 看返回数据结构,应该这里步数的unit可以通过count字符串来实现。
NSInteger allStepsNum = 0; //总数据(不准,只是为了计算手动录入)
NSInteger iphoneStepS = 0; //非手动录入数据(不准,只是为了计算手动录入)
for (HKQuantitySample *sampM in results) {
double allsteps = [sampM.quantity doubleValueForUnit:unit];
NSInteger allstepIntegrs = (NSInteger)allsteps;
allStepsNum += allstepIntegrs;
NSInteger isUserWrite = [sampM.metadata[HKMetadataKeyWasUserEntered] integerValue];
if (isUserWrite == 1) { // 用户手动录入的数据。
}else {
double steps = [sampM.quantity doubleValueForUnit:unit];
NSInteger stepIntegrs = (NSInteger)steps;
iphoneStepS += stepIntegrs;
}
}
if (queryResultBlock) {
//上一步的总数据减去手动录入的数据,就是正确的数据,和微信一致
queryResultBlock(stepCount -(allStepsNum - iphoneStepS),nil);
}
}];
[weakSelf.healthStore executeQuery:hkSQ]; // 执行
}
}];
[self.healthStore executeQuery:query];
}
#pragma mark - 构造当天时间段查询参数
- (NSPredicate *)predicateForSamplesToday {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:0];
[components setMinute:0];
[components setSecond: 0];
NSDate *startDate = [calendar dateFromComponents:components];
NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];
return predicate;
}
#pragma mark - 获取协处理器步数
- (void)getCMPStepCount:(void(^)(double stepCount, NSError *error))completion
{
if ([CMPedometer isStepCountingAvailable] && [CMPedometer isDistanceAvailable]) {
if (!_pedometer) {
_pedometer = [[CMPedometer alloc]init];
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
// 开始时间
NSDate *startDate = [calendar dateFromComponents:components];
// 结束时间
NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
[_pedometer queryPedometerDataFromDate:startDate toDate:endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
if (error) {
if(completion) completion(0 ,error);
[self goAppRunSettingPage];
} else {
double stepCount = [pedometerData.numberOfSteps doubleValue];
if(completion)
completion(stepCount ,error);
}
[_pedometer stopPedometerUpdates];
}];
}
}
#pragma mark - 跳转App运动与健康设置页面
- (void)goAppRunSettingPage {
NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
NSString *msgStr = [NSString stringWithFormat:@"请在【设置->%@->%@】下允许访问权限",appName,@"运动与健身"];
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:msgStr preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:sureAction];
[[UIViewController currentViewController] presentViewController:alertController animated:true completion:nil];
});
}
#pragma mark - getter
- (HKHealthStore *)healthStore {
if (!_healthStore) {
_healthStore = [[HKHealthStore alloc] init];
}
return _healthStore;
}
@end
4 直接调用
- (void)handleInitGetSteps {
MJWeakSelf;
[[HealthKitManager shareInstance] authorizateHealthKit:^(BOOL success, NSError *error) { //检测,授权
[[HealthKitManager shareInstance] getStepCount:^(double stepCount, NSError * _Nonnull error) {
NSInteger stepIntegrs = (NSInteger)stepCount;
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.sportLabel.text = [NSString stringWithFormat:@"%ld", (long)stepIntegrs];
});
}];
}];
}