iOS從健康app中獲取步數信息


統計步數信息並不需要我們自己去實現,iOS自帶的健康app已經為我們統計好了步數數據

我們只要使用HealthKit框架從健康app中獲取這個數據信息就可以了

1.如下圖所示 在Xcode中打開HealthKit功能

2.在需要的地方#import <HealthKit/HealthKit.h>(這里我為了方便直接在viewController寫了所有代碼,我也在學習這個框架,個人感覺把獲取數據權限的代碼放在AppDelegate中更好)

獲取步數分為兩步1.獲得權限  2.讀取步數 

3.代碼部分

1
2
3
4
5
@interface  ViewController ()
 
@property  ( nonatomic , strong) HKHealthStore *healthStore;
 
@end

 在- (void)viewDidLoad中獲取權限

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
- (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(@"獲取步數權限失敗");
        }
    }];
     
}

 讀取步數

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//查詢數據
- (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];
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM