iOS 健康 获取运动步数 距离 时间

时间:2020-12-03 15:44:27

1 把HeathKit打开

iOS 健康 获取运动步数 距离 时间

2 申请权限 包含读和写的 支持iOS8以上 5s及以上

引入头文件

#import <HealthKit/HealthKit.h>
#import <UIKit/UIDevice.h>
#define HKVersion [[[UIDevice currentDevice] systemVersion] doubleValue]#define CustomHealthErrorDomain @"com.sdqt.healthError"

3 申请权限

@property (nonatomic, strong) HKHealthStore *healthStore;
            [self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {                                if (compltion != nil) {                    NSLog(@"error->%@", error.localizedDescription);                    compltion (success, error);                }            }];
4 读和写权限

/*!
* @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];
}

/*!
* @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];
}
5 获取运动步数和时长

//获取步数
- (void)getStepCount:(void(^)(double value, NSError *error))completion{
//HKQuantityTypeIdentifierStepCount 计算步数
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
//排序规则
NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];
//HKObjectQueryNoLimit 数量限制
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;
double sumTime = 0;
//获取数组
for(HKQuantitySample *quantitySample in results){
HKQuantity *quantity = quantitySample.quantity;
HKUnit *heightUnit = [HKUnit countUnit];
double usersHeight = [quantity doubleValueForUnit:heightUnit];
NSLog(@"%f",usersHeight);
totleSteps += usersHeight;

NSDateFormatter *fm=[[NSDateFormatter alloc]init];
fm.dateFormat=@"yyyy-MM-dd HH:mm:ss";
NSString *strNeedStart = [fm stringFromDate:quantitySample.startDate];
NSLog(@"startDate %@",strNeedStart);
NSString *strNeedEnd = [fm stringFromDate:quantitySample.endDate];
NSLog(@"endDate %@",strNeedEnd);
sumTime += [quantitySample.endDate timeIntervalSinceDate:quantitySample.startDate];
}
NSLog(@"当天行走步数 = %ld",(long)totleSteps);
int h = sumTime / 3600;
int m = ((long)sumTime % 3600)/60;
NSLog(@"运动时长:%@小时%@分", @(h), @(m));
completion(totleSteps,error);
}
}];

[self.healthStore executeQuery:query];
}
6 公里数和步数相似

//获取公里数
- (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];
}

/*!
* @brief 当天时间段
*
* @return 时间段
*/
+ (NSPredicate *)predicateForSamplesToday {
//获取日历
NSCalendar *calendar = [NSCalendar currentCalendar];
//获取当前时间
NSDate *now = [NSDate date];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:now];
//设置为0
[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;
}


6 获取数据

    HealthKitManage *manage = [HealthKitManage shareInstance];
[manage authorizeHealthKit:^(BOOL success, NSError *error) {

if (success) {
NSLog(@"success");
[manage getStepCount:^(double value, NSError *error) {
NSLog(@"1count-->%.0f", value);
NSLog(@"1error-->%@", error.localizedDescription);
dispatch_async(dispatch_get_main_queue(), ^{
stepLabel.text = [NSString stringWithFormat:@"步数:%.0f步", value];
});

}];
}
else {
NSLog(@"fail");
}
}];

    HealthKitManage *manage = [HealthKitManage shareInstance];
[manage authorizeHealthKit:^(BOOL success, NSError *error) {

if (success) {
NSLog(@"success");
[manage getDistance:^(double value, NSError *error) {
NSLog(@"2count-->%.2f", value);
NSLog(@"2error-->%@", error.localizedDescription);
dispatch_async(dispatch_get_main_queue(), ^{
distanceLabel.text = [NSString stringWithFormat:@"公里数:%.2f公里", value];
});

}];
}
else {
NSLog(@"fail");
}
}];

Demo

http://download.csdn.net/detail/rpf2014/9862258