iOS HealthKit 查詢步數

https://blog.csdn.net/u012265444/article/details/51861085

Screen Shot 2018-06-01 at 10.29.54 AM.png
Privacy - Health Share Usage Description 
Privacy - Health Update Usage Description
IMG_1292.PNG

//
//  ViewController.m
//  healthKit
//
//  Created by lzy on 2018/6/1.
//  Copyright ? 2018 zbc. All rights reserved.
//

#import "ViewController.h"
#import <HealthKit/HealthKit.h>
@interface ViewController ()

 @property(nonatomic,strong) HKHealthStore *healthStore;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    if (![HKHealthStore isHealthDataAvailable]) {
        NSLog(@"該設備不支持HealthKit");
    }
    
    self.healthStore = [[HKHealthStore alloc]init];
    
    //設置需要獲取的權限 這里僅設置了步數
    HKObjectType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    HKObjectType *HeightType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
        HKObjectType *BodytType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierLeanBodyMass];
    NSSet *healthSet = [NSSet setWithObjects:stepType, HeightType,BodytType,nil];
    
    //從健康應用中獲取權限
    [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            //獲取步數后我們調用獲取步數的方法
            [self readStepCount];
        }
        else
        {
            NSLog(@"獲取步數權限失敗");
        }
    }];
 
}

- (void)readStepCount
{
    //查詢采樣信息
    HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    //NSSortDescriptor來告訴healthStore怎么樣將結果排序
    NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
    NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
    //獲取當前時間
    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)];
    
    /*查詢的基類是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;
        }
        
        //查詢要放在多線程中進行,如果要對UI進行刷新,要回到主線程
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            NSString *str = [NSString stringWithFormat:@"%d",allStepCount];
            NSLog(@"%@",str);
        }];
    }];
    //執行查詢
    [self.healthStore executeQuery:sampleQuery];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容