healthkit 去除人为添加的步数
HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
NSDateComponents *intervalComponents = [[NSDateComponents alloc] init];
__block NSDate *endDate = [NSDate date];
__block NSCalendarUnit calendarUnit;
__block NSCalendar *calendar;
if ([[UIDevice currentDevice] .systemVersion floatValue]>=8.0) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
}
else
{
calendar = [NSCalendar calendarWithIdentifier:NSGregorianCalendar];
}
__block NSInteger value = 0;//根据该值计算查询开始时间
NSDateComponents *currentComponents = [calendar components:NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour fromDate:endDate];
intervalComponents.hour = 1;
calendarUnit = NSCalendarUnitHour;
value = currentComponents.hour;
//查询步数开始时间
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:@"yyyy-MM-dd 00:00:00"];
NSString *currentDateStr1 = [dateFormatter1 stringFromDate:[NSDate date]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *startDate = [dateFormatter dateFromString:currentDateStr1];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate 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) {
_stepCount = 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];
NSString *str = [stepStr componentsSeparatedByString:@" "][0];
NSInteger stepNum = [str integerValue];
NSDictionary *dic = (NSDictionary *)result.metadata;
//人为添加的数据
NSInteger wasUserEntered = [dic[@"HKWasUserEntered"] integerValue];
if (wasUserEntered == 1) {
stepNum = 0;
}
_stepCount +=stepNum;
}
NSString *stepStr = [NSString stringWithFormat:@"%d",_stepCount];
NSDate *currentDate = [NSDate date];//获取当前时间,日期
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:currentDate];
[self.healthStore executeQuery:sampleQuery];
}