1、新建HealthManager继承于NSObject
2、HealthManager.h
#import <Foundation/Foundation.h>
#import <HealthKit/HealthKit.h>
typedef long long long64;
@interface HealthManager : NSObject
@property (retain,nonatomic)HKHealthStore *healthStore;//健康
/*
拉起权限
无论用户是否允许授权,只要当前设备支持
*/
-(void)getHealthDomainCompletion:(void(^)(BOOL success))completion;
/*
获取所有步数记录:
results:数组中包括了今天的所有数据
*/
-(void)getStepTodayCountComplete:(void (^)(BOOL success, NSString *pstrHealthDetail))complete;
//写入步数
- (void)saveStepCount:(double)stepCount;
//判断是否已经开启的权限
-(BOOL)getHealthIsDomain;
@end
3、HealthManager.m
#import "HealthManager.h"
@implementation HealthManager
#pragma mark - HealthKit -
-(BOOL)judgeSupportHk
{
//判断设备是否支持查看healthKit数据
if ([HKHealthStore isHealthDataAvailable]) {
return YES;
}else{
return NO;
}
}
/*
1. HKQuantityTypeIdentifierStepCount 步数
2. HKQuantityTypeIdentifierDistanceWalkingRunning 步行+跑步距离
3. HKQuantityTypeIdentifierDistanceCycling 骑车距离
4. HKQuantityTypeIdentifierBasalEnergyBurned 静息能量
5. HKQuantityTypeIdentifierActiveEnergyBurned 活动能量
6. HKQuantityTypeIdentifierFlightsClimbed 已爬楼层
*/
//需要读权限的集合
- (NSSet *)dataTypesRead
{
HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
return [NSSet setWithObjects:stepCountType,nil];
}
//需要写权限的集合
- (NSSet *)dataTypesToWrite
{
HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
return [NSSet setWithObjects:stepCountType,nil];
}
/*
拉起权限
无论用户是否允许授权,只要当前设备支持,BLOCK回调中都会已成功的形式返回,所以不能作为是否授权判断
*/
-(void)getHealthDomainCompletion:(void(^)(BOOL success))completion{
//判断是否支持健康
BOOL isSupport = [self judgeSupportHk];
if(isSupport==YES){
//创建healthStore实例对象
self.healthStore = [[HKHealthStore alloc]init];
//获取权限
NSSet *healthReadSet = [self dataTypesRead];
//获取权限(暂时不需要写入的权限)
NSSet *healthWriteSet = [self dataTypesToWrite];
/*
1.第一个参数ShareTypes传入一个NSSet类型数据,告知用户,我的App可能会修改你健康数据库中的这些选项数据。
2.第二个参数readTypes也是传入NSSet类型数据,告知用户,我的App可能会从你的数据库中读取以下几项数据。
3.第三个是授权许可回调BOOL值success仅用于判断系统是否支持HealthKit,而不是判断用户是允许OR不允许
*/
[self.h