標籤:
和QQ的每日步數最近十分火爆,我就想為自己寫的項目中添加一個顯示每日步數的功能,上網一搜好像並有相關的詳細資料,自己動手豐衣足食。
統計步數資訊並不需要我們自己去實現,iOS內建的健康app已經為我們統計好了步數資料
我們只要使用HealthKit架構從健康app中擷取這個資料資訊就可以了
這篇文章對HealthKit架構進行了簡單的介紹:http://www.cocoachina.com/ios/20140915/9624.html
對HealthKit架構有了簡單的瞭解後我們就可以開始了
1.如所示 在Xcode中開啟HealthKit功能
2.在需要的地方#import <HealthKit/HealthKit.h>(這裡我為了方便直接在viewController寫了所有代碼,我也在學習這個架構,個人感覺把擷取資料許可權的代碼放在AppDelegate中更好)
擷取步數分為兩步1.獲得許可權 2.讀取步數
3.代碼部分
@interface ViewController ()@property (nonatomic, strong) HKHealthStore *healthStore;@end
在- (void)viewDidLoad中擷取許可權
- (void)viewDidLoad { [super viewDidLoad]; //查看healthKit在裝置上是否可用,ipad不支援HealthKit if(![HKHealthStore isHealthDataAvailable]) { NSLog(@"裝置不支援healthKit"); } //建立healthStore執行個體對象 self.healthStore = [[HKHealthStore alloc] init]; //設定需要擷取的許可權這裡僅設定了步數 HKObjectType *stepCount = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; NSSet *healthSet = [NSSet setWithObjects:stepCount, nil]; //從健康應用中擷取許可權 [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) { if (success) { NSLog(@"擷取步數許可權成功"); //擷取步數後我們調用擷取步數的方法 [self readStepCount]; } else { NSLog(@"擷取步數許可權失敗"); } }]; }
讀取步數
//查詢資料- (void)readStepCount{ //查詢採樣資訊 HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]; //NSSortDescriptors用來告訴healthStore怎麼樣將結果排序。 NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO]; NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO]; /*查詢的基類是HKQuery,這是一個抽象類別,能夠實現每一種查詢目標,這裡我們需要查詢的步數是一個 HKSample類所以對應的查詢類就是HKSampleQuery。 下面的limit參數傳1表示查詢最近一條資料,查詢多條資料只要設定limit的參數值就可以了 */ HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:nil limit:1 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) { //列印查詢結果 NSLog(@"resultCount = %ld result = %@",results.count,results); //把結果裝換成字串類型 HKQuantitySample *result = results[0]; HKQuantity *quantity = result.quantity; NSString *stepStr = (NSString *)quantity; [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //查詢是在多線程中進行的,如果要對UI進行重新整理,要回到主線程中 NSLog(@"最新步數:%@",stepStr); }]; }]; //執行查詢 [self.healthStore executeQuery:sampleQuery];}
4.現在,我們就已經能夠從健康app中讀取步數資訊了
5.附上一個簡單的小demo: https://github.com/wl356485255/ReadStepCount (注意更改Bundle ID,並且使用真機進行調試)
6.我現在也在學習HealthKit架構對這個架構還是比較陌生的,上面只實現了簡單的擷取步數資訊(其他資訊也可以通過相同方式擷取),代碼中有不足的地方希望能夠指出。
iOS利用HealthKit架構從健康app中擷取步數資訊