微信和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框架對這個框架還是比較陌生的,上面只實現了簡單的獲取步數信息(其他信息也可以通過相同方式獲取),代碼中有不足的地方希望能夠指出。
