1.首先打开HealthKit
2.导入HealthKit.framework,并且导入头文件
3.获取步数的写入和读取权限;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self isHealthDataAvailable];
return YES;
}
#pragma mark - 获取健康权限
- (void)isHealthDataAvailable{
if ([HKHealthStore isHealthDataAvailable]) {
HKHealthStore *healthStore = [[HKHealthStore alloc]init];
NSSet *writeDataTypes = [self dataTypesToWrite];
NSSet *readDataTypes = [self dataTypesToRead];
[healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {
if (!success) {
NSLog(@"你不允许包来访问这些读/写数据类型。error === %@", error);
return;
}
}];
}
}
#pragma mark - 设置写入权限
- (NSSet *)dataTypesToWrite {
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
return [NSSet setWithObjects:stepType, nil];
}
#pragma mark - 设置读取权限
- (NSSet *)dataTypesToRead {
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
return [NSSet setWithObjects:stepType, nil];
}
4.获取步数
#pragma mark - 获取步数 刷新界面
- (void)getStepsFromHealthKit{
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
[self fetchSumOfSamplesTodayForType:stepType unit:[HKUnit countUnit] completion:^(double stepCount, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"你的步数为:%.f",stepCount);
});
}];
}
#pragma mark - 读取HealthKit数据
- (void)fetchSumOfSamplesTodayForType:(HKQuantityType *)quantityType unit:(HKUnit *)unit completion:(void (^)(double, NSError *))completionHandler {
NSPredicate *predicate = [self predicateForSamplesToday];
HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {
HKQuantity *sum = [result sumQuantity];
if (completionHandler) {
double value = [sum doubleValueForUnit:unit];
completionHandler(value, error);
}
}];
[self.healthStore executeQuery:query];
}
#pragma mark - NSPredicate数据模型
- (NSPredicate *)predicateForSamplesToday {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startDate = [calendar startOfDayForDate:now];
NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
return [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
}
5.添加步数
#pragma mark - 添加步数
- (void)addstepWithStepNum:(double)stepNum {
HKQuantitySample *stepCorrelationItem = [self stepCorrelationWithStepNum:stepNum];
[self.healthStore saveObject:stepCorrelationItem withCompletion:^(BOOL success, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (success) {
[self.view endEditing:YES];
UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[doneAlertView show];
//刷新数据 重新获取步数
[self getStepsFromHealthKit];
}else {
NSLog(@"The error was: %@.", error);
UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[doneAlertView show];
return ;
}
});
}];
}
#pragma Mark - 获取HKQuantitySample数据模型
- (HKQuantitySample *)stepCorrelationWithStepNum:(double)stepNum {
NSDate *endDate = [NSDate date];
NSDate *startDate = [NSDate dateWithTimeInterval:-300 sinceDate:endDate];
HKQuantity *stepQuantityConsumed = [HKQuantity quantityWithUnit:[HKUnit countUnit] doubleValue:stepNum];
HKQuantityType *stepConsumedType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSString *strName = [[UIDevice currentDevice] name];
NSString *strModel = [[UIDevice currentDevice] model];
NSString *strSysVersion = [[UIDevice currentDevice] systemVersion];
NSString *localeIdentifier = [[NSLocale currentLocale] localeIdentifier];
HKDevice *device = [[HKDevice alloc] initWithName:strName manufacturer:@"Apple" model:strModel hardwareVersion:strModel firmwareVersion:strModel softwareVersion:strSysVersion localIdentifier:localeIdentifier UDIDeviceIdentifier:localeIdentifier];
HKQuantitySample *stepConsumedSample = [HKQuantitySample quantitySampleWithType:stepConsumedType quantity:stepQuantityConsumed startDate:startDate endDate:endDate device:device metadata:nil];
return stepConsumedSample;
}
DEMO下载地址:http://download.csdn.net/detail/u014220518/9642988