iOS开发之-HealthKit

目前公司业务有用到获取Apple-Health里的步数和心率,所以自己初步了解了一下有关于iOS的HealthKit的简单实用
1.target->signing&Capabilities里面点击+capability选择HealthKit如下图所示


添加HealthKit

备注:可以不用勾选Capabilities (1.clinical Healtg Records;2.Background Delivery)
2.info.plist加上隐私权限
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
3.这个时候会自动生成一个EntitlementsFile
4.这个时候就可以着手代码部分。
新建一个HealthManager类

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

//当前健康数据授权的状态
typedef NS_ENUM(NSInteger ,SMHealthAuthorizationStatus){
    SMHealthAuthorizationStatusNotDetermined = 0,
    SMHealthAuthorizationStatusSharingDenied,
    SMHealthAuthorizationStatusSharingAuthorized,
    SMHealthAuthorizationStatusUnsupport,
};

@interface SMHealthManager : NSObject
//@property (nonatomic ,assign)HKAuthorizationStatus stauts;


+ (instancetype)defaultManager;

/**
 请求用户授权
 @param compltion 回调
 */
- (void)requestHealthKitAuthorization:(void(^)(BOOL success, NSError *error))compltion;
 

//获取当天步数
- (void)getStepCount:(void (^)(double stepCount, NSError *error))queryResultBlock;


/**
 获取用户心率
 @param completion 回调   出错时 value = @"--"
 */
- (void)fetchUserHeartRate:(void(^)(NSString *value, NSError *error))completion;
/**
 检查设备是否支持健康数据
 @return yes 支持
 */
- (BOOL)isHealthDataAvailable;
 

//返回当前权限状态
-(SMHealthAuthorizationStatus)appleHealthAuthorizationStatus;
@end

.m文件

#import "SMHealthManager.h"
#import <HealthKit/HealthKit.h>
#import <CoreMotion/CoreMotion.h>
#define IOS8 ([UIDevice currentDevice].systemVersion.floatValue >= 8.0f)
@interface SMHealthManager()

@property (nonatomic,strong) HKHealthStore *healthStore;

@property (nonatomic, strong) HKSample *currentHeartLastSample;

@property (nonatomic, strong) NSMutableArray *currentHeartRateSample;

@property (nonatomic, assign) double currentHeartRateBPM;

@property (nonatomic, strong) NSMutableArray *healthSteps;

/// 协处理器类
@property (nonatomic, strong) CMPedometer *pedometer;


@end

@implementation SMHealthManager
static SMHealthManager *instance = nil;

+ (instancetype)defaultManager
{
    if (!instance) {
        instance = [[super allocWithZone:NULL]init];
        
    }
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [SMHealthManager defaultManager];
}

#pragma mark -授权状态
- (SMHealthAuthorizationStatus)appleHealthAuthorizationStatus
{
    if (![self isHealthDataAvailable]) {
        return  SMHealthAuthorizationStatusSharingDenied;
    }
    
    SMHealthAuthorizationStatus healthStatus = SMHealthAuthorizationStatusSharingDenied;
    HKObjectType *type = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    HKAuthorizationStatus status = [self.healthStore authorizationStatusForType:type];
    switch (status) {
        case HKAuthorizationStatusNotDetermined:
            healthStatus = SMHealthAuthorizationStatusNotDetermined;
            PCLog(@"苹果健康未授权");
            break;
        case HKAuthorizationStatusSharingDenied:
            healthStatus = SMHealthAuthorizationStatusSharingDenied;
            PCLog(@"苹果健康已拒绝");
            break;
        case HKAuthorizationStatusSharingAuthorized:
            healthStatus = SMHealthAuthorizationStatusSharingAuthorized;
            PCLog(@"苹果健康已授权");
            break;
        default:
            break;
    }
    return healthStatus;

}
#pragma mark -授权结果
- (void)requestHealthKitAuthorization:(void (^)(BOOL, NSError * _Nonnull))compltion
{
    if (![self isHealthDataAvailable]) {
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"iOS 系统低于8.0不能获取健康数据,请升级系统"                                                                      forKey:NSLocalizedDescriptionKey];
        NSError *aError = [NSError errorWithDomain:@"com.sleepmonitor.aio" code:0 userInfo:userInfo];
        compltion(NO,aError);
        return;
    }
    HKQuantityType *stepCountType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    HKQuantityType *heartRateType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
    //1.5.0先不上心率
    NSSet *readTypes = [NSSet setWithObjects:stepCountType,nil];
    
    [self.healthStore requestAuthorizationToShareTypes:readTypes readTypes:readTypes completion:^(BOOL success, NSError * _Nullable error) {
        if (compltion) {
            compltion(success,error);
        }
    }];
    
}

#pragma mark - GetStepCount

- (void)getStepCount:(void (^)(double stepCount, NSError *error))queryResultBlock {
    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) {
//            [self getCMPStepCount: queryResultBlock];
            //获取昨天数据
            __block double yesterdayStepCount = 0;
            
            [self getYesterdayStepCount:^(double stepCount, NSError *error) {
                yesterdayStepCount = stepCount;
                if (yesterdayStepCount >0) {
                    queryResultBlock(yesterdayStepCount,nil);
                }else{
                    queryResultBlock(-1,error);
                }
                
            }];
        } else {
            double stepCount = [result.sumQuantity doubleValueForUnit:[HKUnit countUnit]];

            if(stepCount > 0){
                if (queryResultBlock) {
                    queryResultBlock(stepCount,nil);
                }
            } else {
                queryResultBlock(-1,error);
            }
        }
        
    }];
    [self.healthStore executeQuery:query];
}

#pragma mark - GetYesterdayStepCount
- (void)getYesterdayStepCount:(void (^)(double stepCount, NSError *error))queryResultBlock
{
    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    HKStatisticsQuery *query = [[HKStatisticsQuery alloc]initWithQuantityType:quantityType quantitySamplePredicate:[self predicateForSamplesYesterday] options:HKStatisticsOptionCumulativeSum completionHandler:^(HKStatisticsQuery * _Nonnull query, HKStatistics * _Nullable result, NSError * _Nullable error) {
        if (error) {
            queryResultBlock(-1,error);
        } else {
            double stepCount = [result.sumQuantity doubleValueForUnit:[HKUnit countUnit]];
            NSLog(@"当天行走步数 = %lf",stepCount);
            if (queryResultBlock) {
                queryResultBlock(stepCount,nil);
            }
        }
        
    }];
    [self.healthStore executeQuery:query];
}

#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);
            } else {
                double stepCount = [pedometerData.numberOfSteps doubleValue];
                if(completion)
                    completion(stepCount ,error);
            }
            [self->_pedometer stopPedometerUpdates];
        }];
    }
}

//
-(NSDictionary *)collectCurrentHeartRateSample:(NSMutableArray *)currentSampleType{
    NSDictionary *message = [NSDictionary dictionary];
    self.currentHeartRateSample = currentSampleType;
    self.currentHeartLastSample = self.currentHeartRateSample.lastObject;
    if (self.currentHeartLastSample != nil) {
        HKQuantitySample *lastHeartRateSample = (HKQuantitySample *)self.currentHeartRateSample.lastObject;
        self.currentHeartRateBPM =[lastHeartRateSample.quantity doubleValueForUnit:[HKUnit unitFromString:@"count/min"]];
        NSDate *heartRateStartDate = lastHeartRateSample.startDate;
        NSDate *heartRateEndDate = lastHeartRateSample.endDate;
        message = @{@"HeartRateBPM":[NSNumber numberWithDouble:self.currentHeartRateBPM],@"HeartRateStartDate":heartRateStartDate,@"HeartRateEndDate":heartRateEndDate};
    }
    return message;
}

#pragma mark - GetUserHeartRate (传入起止时间)返回一个时间段内的心率数组
- (void)fetchUserHeartRateWithStartTime:(NSInteger)startTime endTime:(NSInteger)endTime andCompletion:(void(^)(NSArray *value, NSError *error))completion
{
     HKQuantityType *heartRate = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
     NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:YES];
     NSMutableArray *mArray = [NSMutableArray array];
     NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:startTime];
     NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:endTime];
     NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];
     HKSampleQuery *query = [[HKSampleQuery alloc]initWithSampleType:heartRate predicate:predicate limit:HKObjectQueryNoLimit sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
        if(error) {
            completion(@[],error);
        } else {
            for (HKSample *sample in results) {
                HKQuantitySample *heartRateSample = (HKQuantitySample *)sample;
               NSInteger heart = [heartRateSample.quantity doubleValueForUnit:[HKUnit unitFromString:@"count/min"]];
                [mArray addObject:[NSString stringWithFormat:@"%ld",heart]];
            }
            completion([mArray copy],error);
        }
    }];
    [self.healthStore executeQuery:query];
}


#pragma mark - isHealthDataAvailable
- (BOOL)isHealthDataAvailable
{
    return [HKHealthStore isHealthDataAvailable];
}


#pragma mark - lazyLoad
- (HKHealthStore *)healthStore
{
    if (!_healthStore) {
        _healthStore = [[HKHealthStore alloc]init];
    }
    return _healthStore;
}


#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 -昨天
- (NSPredicate *)predicateForSamplesYesterday{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *now = [NSDate date];
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:now];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:lastDay];
    [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;
}

@end

备注:HealthKit授权只是单个项目的,比如步数是步数的授权,心率是心率的授权,因为每次传入的type值是不一样的
tips:
授权页面有 allow 和 notallow的只会弹出一次,如不允许后,下次想打开授权就必须进入到设置页面

//跳转到健康数据设置页面
 [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"x-apple-health://app/"] options:@{} completionHandler:^(BOOL success) {
                }];

授权页面,写数据关闭时候,读数据打开,其实相当于未授权;
授权页面,写数据打开时候,读数据关闭,其实相当于无数据;
未完待续。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,179评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,229评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,032评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,533评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,531评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,539评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,916评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,574评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,813评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,568评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,654评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,354评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,937评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,918评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,152评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,852评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,378评论 2 342

推荐阅读更多精彩内容

  • 作者:AppCoda,原文链接,原文日期:2016-03-22译者:Crystal Sun;校对:numbbbbb...
    梁杰_numbbbbb阅读 922评论 0 6
  • 在 iOS 14 正式版发布之前我写了一篇博文《iOS开发之WidgetKit》[https://www.jian...
    YungFan阅读 1,230评论 0 2
  • Demo 展示效果 前言 随着人们对健康的重视,移动端两大巨头Apple和Google都推出了各自的健康库 App...
    Show_Perry阅读 1,477评论 6 10
  • iOS 14 Apple 推出了 WidgetKit,Widget 就像一个迷你版的 App,可以快速访问它所提供...
    YungFan阅读 3,298评论 5 5
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,520评论 28 53