Objective-C通过HealthKit获取步骤数据,如果来自Apple Watch获取Apple观察数据

时间:2017-09-05 09:16:34

标签: ios objective-c health-kit

我通过健康套件(健康应用程序)获取步骤显示以下代码。但如果来源是苹果手表,那么我得到的步骤只有helth app来源iphone。我需要苹果手表中的苹果手表步骤。 如果我有源自苹果手表,我想取苹果手表步骤而不是iphone。

enter code here

-(void)getHistoryoffUserSteps {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *interval = [[NSDateComponents alloc] init];
interval.day = 1;
NSDateComponents *anchorComponents = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
anchorComponents.hour = 0;
NSDate *anchorDate = [calendar dateFromComponents:anchorComponents];
HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
// Create the query
HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:nil options:HKStatisticsOptionCumulativeSum
                                                                                    anchorDate:anchorDate intervalComponents:interval];

query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *results, NSError *error) {
    if (error) {
        // Perform proper error handling here
        NSLog(@"*** An error occurred while calculating the statistics: %@ ***",error.localizedDescription);
    }
    apiStepHistryData=@"";
    NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay
                                           value:-1
                                          toDate:[NSDate date]
                                         options:0];
    NSDate *startDate = [calendar dateByAddingUnit:NSCalendarUnitDay
                                             value:-31
                                            toDate:endDate
                                           options:0];


    [results enumerateStatisticsFromDate:startDate toDate:endDate withBlock:^(HKStatistics *result, BOOL *stop) {
        HKQuantity *quantity = result.sumQuantity;
        if (quantity) {
            NSDate *date = result.startDate;
            NSDateFormatter *format = [[NSDateFormatter alloc]init];
            [format setDateFormat:@"yyyy-MM-dd"];
            NSString*strDate=[format stringFromDate:date];
            double value = [quantity doubleValueForUnit:[HKUnit countUnit]];
            NSString*stepsappend=[NSString stringWithFormat:@"#%.0f",value];
            apiStepHistryData=[NSString stringWithFormat:@"%@,""%@""%@",apiStepHistryData,strDate,stepsappend];


        }

    }

     ];

};

[healthStore executeQuery:query];
dispatch_async(dispatch_get_main_queue(), ^{
[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(apiforUpdateSTepsData) userInfo:nil repeats:NO];

});

}

0 个答案:

没有答案