ios 獲取健康步數(shù),和微信同步

1 首先在開發(fā)者中心 添加 HealhtKit

111.png

2 在info.plist里添加授權(quán)描述,目前只用到了獲取步數(shù)的權(quán)限。


info.png

** Privacy - Motion Usage Description 允許分享步數(shù),以幫助您記錄健康**
** Privacy - Health Update Usage Description 允許更新步數(shù),以幫助您記錄健康**
** Privacy - Health Share Usage Description 允許獲取步數(shù),以幫助您記錄健康**

在xcode中添加


67439ED9-97DA-4802-8432-6367519A6907.png

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;
//授權(quán)檢測
- (void)authorizateHealthKit:(void (^)(BOOL success, NSError *error))resultBlock;

//獲取當天健康數(shù)據(jù)(步數(shù))
- (void)getStepCount:(void (^)(double stepCount, NSError *error))queryResultBlock;

//獲取協(xié)處理器步數(shù)
- (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>

/// 健康數(shù)據(jù)查詢類
@property (nonatomic, strong) HKHealthStore *healthStore;

@property (nonatomic, strong) CMPedometer * pedometer; //步數(shù)協(xié)處理器類

@property (nonatomic, strong) HKObjectType *hkOType; /**< 獲取的權(quán)限 */
@property (nonatomic, strong) HKSampleType *hkSType; /**< 獲取采樣數(shù)據(jù)類型 */


@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 - 應(yīng)用授權(quán)檢查
- (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 - 獲取當天健康數(shù)據(jù)(步數(shù))
- (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 {
             //這里的步數(shù)是總步數(shù),包含手動錄入的,所以要有下面的方法計算出手動錄入的再次減去手動錄入的
             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"];// 看返回數(shù)據(jù)結(jié)構(gòu),應(yīng)該這里步數(shù)的unit可以通過count字符串來實現(xiàn)。
                 NSInteger allStepsNum = 0; //總數(shù)據(jù)(不準,只是為了計算手動錄入)
                  NSInteger iphoneStepS = 0; //非手動錄入數(shù)據(jù)(不準,只是為了計算手動錄入)
                 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) { // 用戶手動錄入的數(shù)據(jù)。
                     }else {
                          double steps = [sampM.quantity doubleValueForUnit:unit];
                          NSInteger stepIntegrs = (NSInteger)steps;
                          iphoneStepS += stepIntegrs;
                     }
                 }
                  if (queryResultBlock) {
                       //上一步的總數(shù)據(jù)減去手動錄入的數(shù)據(jù),就是正確的數(shù)據(jù),和微信一致
                      queryResultBlock(stepCount -(allStepsNum - iphoneStepS),nil);
                  }
             }];
             [weakSelf.healthStore executeQuery:hkSQ]; // 執(zhí)行
        }
    }];
    [self.healthStore executeQuery:query];
}

#pragma mark - 構(gòu)造當天時間段查詢參數(shù)
- (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 - 獲取協(xié)處理器步數(shù)
- (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];
        // 結(jié)束時間
        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 - 跳轉(zhuǎn)App運動與健康設(shè)置頁面
- (void)goAppRunSettingPage {
    NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
    NSString *msgStr = [NSString stringWithFormat:@"請在【設(shè)置->%@->%@】下允許訪問權(quán)限",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 直接調(diào)用

- (void)handleInitGetSteps {
     MJWeakSelf;
     [[HealthKitManager shareInstance] authorizateHealthKit:^(BOOL success, NSError *error) { //檢測,授權(quán)
          [[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];
               });
          }];
     }];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容