/** 前段时间iOS 健康数据非常的火,我忍不住寂寞,写了一个博客:
* @title: iOS利用HealthKit框架从健康app中获取步数信息
*
* 1.第一步首先需要开启HealthKit
* TARGETS -> Capabilities -> HealthKit -> YES
*
* 在此目录栏下,有一个steps,会显示一个❌(图片如下:health.png)
* eg:add the "HealthKit" entitlement to your app id
* 这是 你可能需要Fix issue ,这时候可能会在项目中出现.entitlements文件
* 相关处理请自行查资料直到ok为止
*
* 2.新建一个HealthKitManage类,继承于NSObject
* (1)导入头文件
* #import <HealthKit/HealthKit.h>
* #import <UIKit/UIKit.h>
* #define HKVersion [[[UIDevice currentDevice] systemVersion] doubleValue]
* #define CustomHealthErrorDomain @"com.sdqt.healthError
* 相关的方法请自行查看 HealthKitManage.h & HealthKitManage.m 文件(已封装)
*
* 3.相关的调用
* HealthKitManage *manage = [HealthKitManage shareInstance];
* 然后调用相关的方法(对象+ 方法名)
*
* 4.参考博客:http://www.jianshu.com/p/1dd6ad5b1520
*/
下面直接上代码:
#import <Foundation/Foundation.h>
#import <HealthKit/HealthKit.h>
#import <UIKit/UIKit.h>
@interface HealthKitManage :NSObject
@property(nonatomic,strong)HKHealthStore *healthStore;
/**
* 2.创建单例
*/
+(id)shareInstance;
/*
* 3.检查是否支持获取健康数据
* @brief 检查是否支持获取健康数据
*/
- (void)authorizeHealthKit:(void(^)(BOOL success,NSError *error))compltion;
/*
* 4.获取步数
*/
- (void)getStepCount:(void(^)(double value,NSError *error))completion;
/**
* 5.获取公里数
* 读取步行+跑步距离
*/
- (void)getDistance:(void(^)(double value,NSError *error))completion;
@end
//
// HealthKitManage.m
// 启动屏加启动广告页
//
// Created by administrator on 16/9/12.
// Copyright © 2016年 WOSHIPM. All rights reserved.
//
#import "HealthKitManage.h"
/* 1.导入头文件 */
#define HKVersion [[[UIDevice currentDevice] systemVersion] doubleValue]
#define CustomHealthErrorDomain @"com.sdqt.healthError"
@implementation HealthKitManage
/**
* 2.创建单例
*/
+(id)shareInstance
{
static id manager ;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[[selfclass] alloc]init];
});
return manager;
}
/*
* 3.检查是否支持获取健康数据
* @brief 检查是否支持获取健康数据
*/
- (void)authorizeHealthKit:(void(^)(BOOL success,NSError *error))compltion
{
if(HKVersion >=8.0) {
if (![HKHealthStoreisHealthDataAvailable]) {
NSError *error = [NSErrorerrorWithDomain: @"com.raywenderlich.tutorials.healthkit"code: 2 userInfo: [NSDictionary dictionaryWithObject:@"HealthKit is not available in th is Device" forKey:NSLocalizedDescriptionKey]];
if (compltion != nil) {
compltion(false, error);
}
return;
}
if ([HKHealthStoreisHealthDataAvailable]) {
if(self.healthStore ==nil)
self.healthStore = [[HKHealthStorealloc] init];
/*
组装需要读写的数据类型
*/
NSSet *writeDataTypes = [selfdataTypesToWrite];
NSSet *readDataTypes = [selfdataTypesRead];
/*
注册需要读写的数据类型,也可以在“健康”APP中重新修改
*/
[self.healthStorerequestAuthorizationToShareTypes:writeDataTypesreadTypes:readDataTypes completion:^(BOOL success, NSError *error) {
if (compltion != nil) {
NSLog(@"error->%@", error.localizedDescription);
compltion (success, error);
}
}];
}
}else {
NSDictionary *userInfo = [NSDictionarydictionaryWithObject:@"iOS系统低于8.0" forKey:NSLocalizedDescriptionKey];
NSError *aError = [NSErrorerrorWithDomain:CustomHealthErrorDomaincode:0 userInfo:userInfo];
compltion(0,aError);
}
}
/*! 3.1
* @brief 写权限
* @return 集合
* 设置需要获取的权限:
*/
- (NSSet *)dataTypesToWrite
{
HKQuantityType *heightType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
HKQuantityType *weightType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
HKQuantityType *temperatureType = [HKQuantityTypequantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature];
HKQuantityType *activeEnergyType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
return [NSSetsetWithObjects:heightType, temperatureType, weightType,activeEnergyType,nil];
}
/*! 3.2
* @brief 读权限
* @return 集合
*/
- (NSSet *)dataTypesRead
{
HKQuantityType *heightType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
HKQuantityType *weightType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
HKQuantityType *temperatureType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature];
HKCharacteristicType *birthdayType = [HKObjectTypecharacteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth];
HKCharacteristicType *sexType = [HKObjectTypecharacteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex];
HKQuantityType *stepCountType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKQuantityType *distance = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
HKQuantityType *activeEnergyType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];
return [NSSetsetWithObjects:heightType, temperatureType,birthdayType,sexType,weightType,stepCountType, distance, activeEnergyType,nil];
}
/*
* 4.获取步数
*/
- (void)getStepCount:(void(^)(double value,NSError *error))completion
{
HKQuantityType *stepType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
/** NSSortDescriptors用来告诉healthStore怎么样将结果排序。
*
* NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
*
*/
NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptoralloc] initWithKey:HKSampleSortIdentifierEndDateascending:NO];
// Since we are interested in retrieving the user's latest sample, we sort the samples in descending order, and set the limit to 1. We are not filtering the data, and so the predicate is set to nil.
/*查询的基类是HKQuery,这是一个抽象类,能够实现每一种查询目标,这里我们需要查询的步数是一个
HKSample类所以对应的查询类就是HKSampleQuery。
下面的limit参数传1表示查询最近一条数据,查询多条数据只要设置limit的参数值就可以了
*/
HKSampleQuery *query = [[HKSampleQueryalloc] initWithSampleType:stepTypepredicate:[HealthKitManagepredicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[timeSortDescriptor]resultsHandler:^(HKSampleQuery *query,NSArray *results, NSError *error) {
if(error) {
completion(0,error);
}else {
NSInteger totleSteps = 0;
for(HKQuantitySample *quantitySamplein results) {
HKQuantity *quantity = quantitySample.quantity;
HKUnit *heightUnit = [HKUnitcountUnit];
double usersHeight = [quantity doubleValueForUnit:heightUnit];
totleSteps += usersHeight;
}
NSLog(@"当天行走步数 = %ld",(long)totleSteps);
completion(totleSteps,error);
}
}];
[self.healthStoreexecuteQuery:query];/*执行查询 */
}
/**
* 5.获取公里数
* 读取步行+跑步距离
*/
- (void)getDistance:(void(^)(double value,NSError *error))completion
{
HKQuantityType *distanceType = [HKObjectTypequantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptoralloc] initWithKey:HKSampleSortIdentifierEndDateascending:NO];
HKSampleQuery *query = [[HKSampleQueryalloc] initWithSampleType:distanceTypepredicate:[HealthKitManagepredicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[timeSortDescriptor]resultsHandler:^(HKSampleQuery *_Nonnull query, NSArray<__kindofHKSample *> * _Nullable results,NSError * _Nullable error) {
if(error){
completion(0,error);
}else{
double totleSteps = 0;
for(HKQuantitySample *quantitySamplein results){
HKQuantity *quantity = quantitySample.quantity;
HKUnit *distanceUnit = [HKUnitmeterUnitWithMetricPrefix:HKMetricPrefixKilo];
double usersHeight = [quantity doubleValueForUnit:distanceUnit];
totleSteps += usersHeight;
}
NSLog(@"当天行走距离 = %.2f",totleSteps);
completion(totleSteps,error);
}
}];
[self.healthStoreexecuteQuery:query];
}
/*! 6.NSPredicate当天时间段的方法实现
* @brief 当天时间段
*
* @return 时间段
*/
+ (NSPredicate *)predicateForSamplesToday {
NSCalendar *calendar = [NSCalendarcurrentCalendar];
NSDate *now = [NSDatedate];
NSDateComponents *components = [calendarcomponents:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDayfromDate:now];
[componentssetHour:0];
[componentssetMinute:0];
[componentssetSecond: 0];
NSDate *startDate = [calendar dateFromComponents:components];
NSDate *endDate = [calendardateByAddingUnit:NSCalendarUnitDayvalue:1toDate:startDate options:0];
NSPredicate *predicate = [HKQuerypredicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];
return predicate;
}
@end