一. 使用框架
1.png
打開按鈕之后,左側會自動導入框架
2.png
在需要使用的頁面導入框架#import <HealthKit/HealthKit.h>
二. 代碼部分
首先聲明一個HKHealthStore類的實例,去獲取在健康里面獲取數據的權限,在iPad上面是不支持此框架的,所以我們要進行一個判斷:
if (![HKHealthStore isHealthDataAvailable]) { NSLog(@"該設備不支持HealthKit"); }
如果不是iPad正式開始獲取權限:
//創建healthStore對象
self.healthStore = [[HKHealthStore alloc]init];
//設置需要獲取的權限 這里僅設置了步數
HKObjectType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSet *healthSet = [NSSet setWithObjects:stepType, nil];
//從健康應用中獲取權限
[self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
if (success) {
//獲取步數后我們調用獲取步數的方法
[self readStepCount];
} else {
NSLog(@"獲取步數權限失敗");
}
}];
接下來需要實現獲取步數的方法代碼:
(1)查詢采樣信息
HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
(2)NSSortDescriptor來告訴healthStore怎么樣將結果排序
NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
(3)由于健康中的數據也是通過時間來獲取的,所以這里我們要獲取當前時間進行對比
NSDate *now = [NSDate date];
NSCalendar *calender = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *dateComponent = [calender components:unitFlags fromDate:now];
int hour = (int)[dateComponent hour];
int minute = (int)[dateComponent minute];
int second = (int)[dateComponent second];
NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow: - (hour*3600 + minute * 60 + second) ];
//時間結果與想象中不同是因為它顯示的是0區 NSLog(@"今天%@",nowDay);
NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow: - (hour*3600 + minute * 60 + second) + 86400];
NSLog(@"明天%@",nextDay);
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nowDay endDate:nextDay options:(HKQueryOptionNone)];
(4)查詢的基類是HKQuery,這是一個抽象類,能夠實現每一種查詢目標,這里我們需要查詢的步數是一個HKSample類所以對應的查詢類是HKSampleQuery。下面的limit參數傳1表示查詢最近一條數據,查詢多條數據只要設置limit的參數值就可以了
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc]initWithSampleType:sampleType predicate:predicate limit:0 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
//設置一個int型變量來作為步數統計 int allStepCount = 0;
for (int i = 0; i < results.count; i ++) {
//把結果轉換為字符串類型
HKQuantitySample *result = results[i];
HKQuantity *quantity = result.quantity;
NSMutableString *stepCount = (NSMutableString *)quantity;
NSString *stepStr =[ NSString stringWithFormat:@"%@",stepCount];
//獲取51 count此類字符串前面的數字
NSString *str = [stepStr componentsSeparatedByString:@" "][0];
int stepNum = [str intValue];
NSLog(@"%d",stepNum);
//把一天中所有時間段中的步數加到一起
allStepCount = allStepCount + stepNum;
}
NSLog(@"今天的總步數====%d",allStepCount); }];
(5)開始執行查詢
[self.healthStore executeQuery:sampleQuery];
這樣就實現了獲取今天到現在為止的步數