利用系统healthKit获取每天运动的步数

在运动型或者健康管理类的项目当中HeathKit是必不可少的他可以获取到用户的健康数据

iOS8以后苹果系统增加了健康手,开发者可以利用HealthKit获取到系统的步数信息

1. 要获取到用户的权限,经过用户同意之后才能获取到健康数据


![44198C07-B52D-4441-A315-98CE1689320B.png](http://upload-images.jianshu.io/upload_images/1765107-fad27efa7f41b8c1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

   if (![HKHealthStore isHealthDataAvailable]) {
    
        NSLog(@"不支持获取步数");
}
    self.healthStore = [[HKHealthStore alloc] init];

//设置需要获取的权限
    HKObjectType *objectType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    NSSet *healthSet = [NSSet setWithObjects:objectType,nil];
    [self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
    if (success) {   
        //获取步数的方法接下来去实现这个方法
        [self readStepCount];
        }
  }];


2. #pragma mark -- /*获取步数方法*/
- (void)readStepCount {

    HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

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

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

//获取当前的时间进行对比
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents * dateComponents = [calendar components:unitFlags fromDate:date];

    int hour = (int)dateComponents.hour;
    int minute = (int)dateComponents.minute;
    int second = (int)dateComponents.second;
    NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow:-(hour *3600 + minute * 360 + second)];
    NSLog(@"今天%@",nowDay);
    NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow:- (hour *3600 + minute * 360 + second) + 86400];
    NSLog(@"明天%@",nextDay);
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:nowDay endDate:nextDay options:HKQueryOptionNone];
    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 allStepCount = 0;
        for (int i = 0; i < results.count ; i++) {
            HKQuantitySample *result = results[i];
            HKQuantity *quantity = result.quantity;
            NSMutableString *mutableString = (NSMutableString *)quantity;
            NSString *step = [NSString stringWithFormat:@"%@",mutableString];
        //获取51 count此类字符串前面的数字
            NSString *str = [step componentsSeparatedByString:@" "][0];
            int stepNum = [str intValue];
            NSLog(@"%d",stepNum);
        //把一天中所有时间段中的步数加到一起
            allStepCount = allStepCount + stepNum;
        }
        self.countLabel.text = [NSString stringWithFormat:@"你今天走了%d",allStepCount];
    }];
    [self.healthStore  executeQuery:sampleQuery];    
}

推荐阅读更多精彩内容