HKObserver updateHandler остановить выполнение

Мне нужно загрузить шаги на сервер, даже если приложение находится в фоновом режиме. Я добавил HKObserverQuery с enableBackgroundDeliveryForType для HKQuantityTypeIdentifierStepCount.

Когда уведомление об обновлении получено от наблюдателя, оно запрашивает общее количество шагов за один день (HKStatisticsCollectionQuery).

До этого все работало нормально, после того как процесс выполнения запроса остановился, результат не получен. Шаги есть в исправности Apple, но результат не возвращается.

Может кто-нибудь знает, почему это остановило или не вернул результат?

[healthStore enableBackgroundDeliveryForType: [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount] frequency:HKUpdateFrequencyImmediate withCompletion:^(BOOL success, NSError *error) {
    NSLog(@"Delegate Observation registered error for steps=%@",error);
}];

HKobserverQuery и enableBackgroundDeliveryForType добавлены из didFinishLaunchingWithOptions.

HKSampleType *quantityType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

HKObserverQuery *query =
[[HKObserverQuery alloc]
 initWithSampleType:quantityType
 predicate:nil
 updateHandler:^(HKObserverQuery *query,
                 HKObserverQueryCompletionHandler completionHandler,
                 NSError *error) {

      CustomClass *customVC = [[CustomClass alloc] init];
             [customVC fetchSteps:completionHandler];

 }];
[self.healthApp.healthStore executeQuery:query];

Я создал пользовательский класс, который выбирает шаги из Apple Health и загружает их на сервер, ниже приведен код метода, который выбирает шаги.

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *interval = [[NSDateComponents alloc] init];
interval.day = 1;

// Set the anchor date to Monday at 3:00 a.m.
NSDateComponents *anchorComponents =
[calendar components:NSCalendarUnitDay | NSCalendarUnitMonth |
 NSCalendarUnitYear fromDate:[NSDate date]];

anchorComponents.day -= 1;
anchorComponents.hour = 0;

NSDate *anchorDate = [calendar dateFromComponents:anchorComponents];

NSLog(@"Anchor date::::: %@",anchorDate);

HKQuantityType *quantityType =
[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];


// Create the query
HKStatisticsCollectionQuery *query =
[[HKStatisticsCollectionQuery alloc]
 initWithQuantityType:quantityType
 quantitySamplePredicate:nil
 options:HKStatisticsOptionCumulativeSum
 anchorDate:anchorDate
 intervalComponents:interval];

// Set the results handler
query.initialResultsHandler =
^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *results, NSError *error) {

    if (error) {

        NSLog(@"An error occurred while calculating the statistics:::: %@",error);
        return ;

    }

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    NSDateFormatter *formate=[[NSDateFormatter alloc] init];
    [formate setTimeZone:[NSTimeZone localTimeZone]];
    [formate setDateFormat:@"yyyy-MM-dd"];

    NSDate *startDate;
    NSDate *endDate;

    NSLog(@"Current date::: %@",startdt);
    NSString *dateStr = [formate stringFromDate:startdt];
    startDate = [formate dateFromString:dateStr];

    dateStr = [NSString stringWithFormat:@"%@ 23:59:59",dateStr];
    [formate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    endDate = [formate dateFromString:dateStr];

    [components setDay:-1];
    startDate = [cal dateByAddingComponents:components toDate:startDate options:0];


    NSDateFormatter *form=[[NSDateFormatter alloc] init];
    [form setDateFormat:@"dd-MM-yyyy HH:mm:ss"];


    // Gether all data
    [results
     enumerateStatisticsFromDate:startDate
     toDate:endDate
     withBlock:^(HKStatistics *result, BOOL *stop) {

         HKQuantity *quantity = result.sumQuantity;
         if (quantity) {

             double value = [quantity doubleValueForUnit:hkUnit];

             NSString *strValue = [NSString stringWithFormat:@"%f",value];
             NSDate *date = result.startDate;

             [self uploadSteps:date steps:strValue];

         }

     }];


};

[self.healthStore executeQuery:query];

Если приведенной информации недостаточно, пожалуйста, спросите любую. Я не знаю, что я сделал не так.

0 ответов

Другие вопросы по тегам