iOS開發(fā)-----使用HealthKit獲取步數(shù)

一. 使用框架

1.png

打開按鈕之后,左側(cè)會(huì)自動(dòng)導(dǎo)入框架


2.png

在需要使用的頁(yè)面導(dǎo)入框架#import <HealthKit/HealthKit.h>

二. 代碼部分
首先聲明一個(gè)HKHealthStore類的實(shí)例,去獲取在健康里面獲取數(shù)據(jù)的權(quán)限,在iPad上面是不支持此框架的,所以我們要進(jìn)行一個(gè)判斷:

if (![HKHealthStore isHealthDataAvailable]) { NSLog(@"該設(shè)備不支持HealthKit"); }

如果不是iPad正式開始獲取權(quán)限:

//創(chuàng)建healthStore對(duì)象 
self.healthStore = [[HKHealthStore alloc]init]; 
//設(shè)置需要獲取的權(quán)限 這里僅設(shè)置了步數(shù) 
HKObjectType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; 
NSSet *healthSet = [NSSet setWithObjects:stepType, nil]; 
//從健康應(yīng)用中獲取權(quán)限 
[self.healthStore requestAuthorizationToShareTypes:nil  readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
 if (success) {
 //獲取步數(shù)后我們調(diào)用獲取步數(shù)的方法
 [self readStepCount]; 
} else {
 NSLog(@"獲取步數(shù)權(quán)限失敗"); 
}
 }];

接下來(lái)需要實(shí)現(xiàn)獲取步數(shù)的方法代碼:
(1)查詢采樣信息

HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

(2)NSSortDescriptor來(lái)告訴healthStore怎么樣將結(jié)果排序

NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO]; 
NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];

(3)由于健康中的數(shù)據(jù)也是通過(guò)時(shí)間來(lái)獲取的,所以這里我們要獲取當(dāng)前時(shí)間進(jìn)行對(duì)比

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) ]; 
//時(shí)間結(jié)果與想象中不同是因?yàn)樗@示的是0區(qū) 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,這是一個(gè)抽象類,能夠?qū)崿F(xiàn)每一種查詢目標(biāo),這里我們需要查詢的步數(shù)是一個(gè)HKSample類所以對(duì)應(yīng)的查詢類是HKSampleQuery。下面的limit參數(shù)傳1表示查詢最近一條數(shù)據(jù),查詢多條數(shù)據(jù)只要設(shè)置limit的參數(shù)值就可以了

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) { 
//設(shè)置一個(gè)int型變量來(lái)作為步數(shù)統(tǒng)計(jì) int allStepCount = 0; 
for (int i = 0; i < results.count; i ++) { 
//把結(jié)果轉(zhuǎn)換為字符串類型 
HKQuantitySample *result = results[i]; 
HKQuantity *quantity = result.quantity; 
NSMutableString *stepCount = (NSMutableString *)quantity;
 NSString *stepStr =[ NSString stringWithFormat:@"%@",stepCount]; 
//獲取51 count此類字符串前面的數(shù)字
 NSString *str = [stepStr componentsSeparatedByString:@" "][0]; 
int stepNum = [str intValue];
 NSLog(@"%d",stepNum);
 //把一天中所有時(shí)間段中的步數(shù)加到一起 
allStepCount = allStepCount + stepNum;
 } 
NSLog(@"今天的總步數(shù)====%d",allStepCount); }];

(5)開始執(zhí)行查詢

[self.healthStore executeQuery:sampleQuery];

這樣就實(shí)現(xiàn)了獲取今天到現(xiàn)在為止的步數(shù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容