/**
- @title: iOS利用HealthKit框架从健康app中获取步数信息
- 1.第一步首先需要开启HealthKit
- TARGETS -> Capabilities -> HealthKit -> YES
- 在此目录栏下,有一个steps,会显示一个❌
- 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
//------------------------------------------------
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 = [[[self class] alloc] init];
});
return manager;
}
/*
- 3.检查是否支持获取健康数据
- @brief 检查是否支持获取健康数据
*/
-
(void)authorizeHealthKit:(void(^)(BOOL success, NSError *error))compltion
{
if(HKVersion >= 8.0) {
if (![HKHealthStore isHealthDataAvailable]) {
NSError error = [NSError errorWithDomain: @"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 ([HKHealthStore isHealthDataAvailable]) {
if(self.healthStore == nil)
self.healthStore = [[HKHealthStore alloc] init];
/
组装需要读写的数据类型
*/
NSSet *writeDataTypes = [self dataTypesToWrite];
NSSet *readDataTypes = [self dataTypesRead];/* 注册需要读写的数据类型,也可以在“健康”APP中重新修改 */ [self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) { if (compltion != nil) { NSLog(@"error->%@", error.localizedDescription); compltion (success, error); } }]; }
}else {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"iOS 系统低于8.0" forKey:NSLocalizedDescriptionKey];
NSError *aError = [NSError errorWithDomain:CustomHealthErrorDomain code:0 userInfo:userInfo];
compltion(0,aError);
}
}
/*! 3.1
- @brief 写权限
- @return 集合
- 设置需要获取的权限:
*/
-
(NSSet *)dataTypesToWrite
{
HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
HKQuantityType *temperatureType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature];
HKQuantityType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];return [NSSet setWithObjects:heightType, temperatureType, weightType,activeEnergyType,nil];
}
/*! 3.2
- @brief 读权限
- @return 集合
*/
-
(NSSet *)dataTypesRead
{
HKQuantityType *heightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
HKQuantityType *weightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
HKQuantityType *temperatureType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyTemperature];
HKCharacteristicType *birthdayType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth];
HKCharacteristicType *sexType = [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex];
HKQuantityType *stepCountType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKQuantityType *distance = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
HKQuantityType *activeEnergyType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned];return [NSSet setWithObjects:heightType, temperatureType,birthdayType,sexType,weightType,stepCountType, distance, activeEnergyType,nil];
}
/*
- 4.获取步数
*/
-
(void)getStepCount:(void(^)(double value, NSError *error))completion
{
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];/** NSSortDescriptors用来告诉healthStore怎么样将结果排序。
- NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
*/
NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending: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 = [[HKSampleQuery alloc] initWithSampleType:stepType predicate:[HealthKitManage predicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
if(error) {
completion(0,error);
} else {
NSInteger totleSteps = 0;
for(HKQuantitySample *quantitySample in results) {
HKQuantity *quantity = quantitySample.quantity;
HKUnit *heightUnit = [HKUnit countUnit];
double usersHeight = [quantity doubleValueForUnit:heightUnit];
totleSteps += usersHeight;
}
NSLog(@"当天行走步数 = %ld",(long)totleSteps);
completion(totleSteps,error);
}
}];[self.healthStore executeQuery:query];/* 执行查询 */
}
/**
- 5.获取公里数
- 读取步行+跑步距离
*/
-
(void)getDistance:(void(^)(double value, NSError *error))completion
{
HKQuantityType *distanceType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:distanceType predicate:[HealthKitManage predicateForSamplesToday] limit:HKObjectQueryNoLimit sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {if(error){ completion(0,error); }else{ double totleSteps = 0; for(HKQuantitySample *quantitySample in results){ HKQuantity *quantity = quantitySample.quantity; HKUnit *distanceUnit = [HKUnit meterUnitWithMetricPrefix:HKMetricPrefixKilo]; double usersHeight = [quantity doubleValueForUnit:distanceUnit]; totleSteps += usersHeight; } NSLog(@"当天行走距离 = %.2f",totleSteps); completion(totleSteps,error); }
}];
[self.healthStore executeQuery:query];
}
/*! 6.NSPredicate当天时间段的方法实现
- @brief 当天时间段
- @return 时间段
*/
-
(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;
}
@end
网友评论