1,Xcode 8之後需要在info.plist 中設置以下兩個權限;
(1)Privacy - Health update Usage Description
(2)Privacy - Health Share Usage Description
2,導入頭文件;
#import <HealthKit/HealthKit.h>
#import <UIKit/UIDevice.h>
3,設置讀取數據的權限和寫入數據的權限
#pragma mark - 設置寫入權限
- (NSSet *)dataTypesToWrite {
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKQuantityType *distanceType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
return [NSSet setWithObjects:stepType,distanceType, nil];
}
#pragma mark - 設置讀取權限
- (NSSet *)dataTypesToRead {
以下為設置的權限類型:
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKQuantityType *distanceType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
return [NSSet setWithObjects:stepType,distanceType, nil];
}
以下是關於fitness的全部權限介紹可以直接去看HKQuantityType.h文件很詳細,有//fitness,// Body Measurements,// Results,// Vitals等
// Fitness
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierStepCount HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Scalar(Count), Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceWalkingRunning HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Length, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceCycling HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Length, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceWheelchair HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0); // Length, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierBasalEnergyBurned HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Energy, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierActiveEnergyBurned HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Energy, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierFlightsClimbed HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Scalar(Count), Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierNikeFuel HK_AVAILABLE_IOS_WATCHOS(8_0, 2_0); // Scalar(Count), Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierAppleExerciseTime HK_AVAILABLE_IOS_WATCHOS(9_3, 2_2); // Time Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierPushCount HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0); // Scalar(Count), Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierDistanceSwimming HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0); // Length, Cumulative
HK_EXTERN HKQuantityTypeIdentifier const HKQuantityTypeIdentifierSwimmingStrokeCount HK_AVAILABLE_IOS_WATCHOS(10_0, 3_0); // Scalar(Count), Cumulative
4,判斷設備是否支持
if(![HKHealthStore isHealthDataAvailable]){
NSLog(@"設備不支持healthkit");
}
5,獲取權限和獲取數據
// 此處獲取權限的寫入和讀取 獲取之後才可以加到數據中
NSSet *writeDataTypes = [self dataTypesToWrite];
NSSet *readDataTypes = [self dataTypesToRead];
[self.healthstore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError * _Nullable error) {
if (success) {
[self getStepsFromHealthKit];//第二種獲取方法
// [self getdistanceFromHealthKit]; //獲取公裏數
}else{
}
}];
6,獲取具體的數據的方法,三個方法是一起的//unit此處需要註意的是單位的不同
- (void)getDistancesFromHealthKit{
HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
[self fetchSumOfSamplesTodayForType:stepType unit:[HKUnit meterUnit] completion:^(double stepCount, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"你的公裏數為:%.f",stepCount);
self.pedoLab.text = [NSString stringWithFormat:@"%.2fm",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];
NSLog(@"result ==== %@",result);
if (completionHandler) {
double value = http://www.ithao123.cn/[sum doubleValueForUnit:unit];
NSLog(@"sum ==== %@",sum);
NSLog(@"value =http://www.ithao123.cn/==%f",value);
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];
}
7,添加和寫入數據,並重新獲取數據
#pragma mark - 添加步數
- (void)adddistanceWithStepNum:(double)stepNum {
HKQuantitySample *stepCorrelationItem = [self distanceCorrelationWithStepNum: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 getDistancesFromHealthKit];
}else {
NSLog(@"The error was: %@.", error);
UIAlertView *doneAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"添加失敗" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
[doneAlertView show];
return ;
}
});
}];
}
- (HKQuantitySample *)distanceCorrelationWithStepNum:(double)stepNum {
NSDate *endDate = [NSDate date];
NSDate *startDate = [NSDate dateWithTimeInterval:-300 sinceDate:endDate];
/**
//這裏的quantityWithUnit單位如果不對則會報錯註意 ,有以下單位獲取下面的對應的健康數據需要註意
+ (instancetype)meterUnitWithMetricPrefix:(HKMetricPrefix)prefix; // m
+ (instancetype)meterUnit; // m
+ (instancetype)inchUnit; // in
+ (instancetype)footUnit; // ft
+ (instancetype)yardUnit HK_AVAILABLE_IOS_WATCHOS(9_0, 2_0); // yd
+ (instancetype)mileUnit; // mi
**/
HKQuantity *stepQuantityConsumed = [HKQuantity quantityWithUnit:[HKUnit meterUnit] doubleValue:stepNum];
HKQuantityType *stepConsumedType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
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;
}
Tags: fitness return Health import 健康
文章來源: