我正在編寫一個簡單的應用程序,以便每當將新的健康速率值寫入HealthKit時,從HealthKit監視心率(HKQuantityTypeIdentifierHeartRate)。監測來自HealthKit的心率 - >僅在applicationDidBecomeActive(BUG或FEATURE?)後調用HKAnchoredObjectQuery
正如在WWDC2015(會話203)中看到的,我使用的是HKAnchoredObjectQuery,它應該用於添加和刪除對象。每當我啓動應用程序,我打電話HKQuery爲最新的對象和執行查詢哪些工作正常!但即使樣本在那裏,我也沒有新的樣本,但如果我將應用程序帶到背景並再次到達前景,我將獲得所有新的心率。它是一個錯誤嗎?或者我應該怎麼做才能在不將應用程序帶到後臺和前臺的情況下監控心率?
這裏是我使用的(一切都存儲在AppDelegate中)的代碼,我打電話[self requestAccessDataTypes];
從didFinishLaunchingWithOptions:
[healthStore enableBackgroundDeliveryForType:sampleType frequency:HKUpdateFrequencyImmediate withCompletion:^(BOOL success, NSError *error) {}];
HKQuery *query = [self createHeartRateStreamingQuery:datum];
if (query) {
[healthStore executeQuery:query];
}
else
{
NSLog(@"workout can not start");
}
-(HKQuery*)createHeartRateStreamingQuery:(NSDate*)workoutStartDate
{
NSLog(@"%@ - createHeartRateStreamingQuery", [self class]);
if ([HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate]) {
HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
HKAnchoredObjectQuery * heartRateQuery = [[HKAnchoredObjectQuery alloc] initWithType:quantityType predicate:nil anchor:anchor limit:HKObjectQueryNoLimit resultsHandler:^(HKAnchoredObjectQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable sampleObjects, NSArray<HKDeletedObject *> * _Nullable deletedObjects, HKQueryAnchor * _Nullable newAnchor, NSError * _Nullable error) {
if (!error) {
anchor = newAnchor;
[self updateHeartRate:sampleObjects];
}
}];
heartRateQuery.updateHandler = ^void(HKAnchoredObjectQuery *query, NSArray<__kindof HKSample *> * __nullable addedObjects, NSArray<HKDeletedObject *> * __nullable deletedObjects, HKQueryAnchor * __nullable newAnchor, NSError * __nullable error)
{
if (!error) {
anchor = newAnchor;
[self updateHeartRate:addedObjects];
}
};
return heartRateQuery;
}
return nil;
}
感謝您的回答,但我正在使用自動將HealthKit數據從手錶傳輸到父應用程序,並且正如我在請求中所寫的那樣,數據或多或少地實時傳輸!每當我啓動應用程序時,我都會爲最新的對象調用HKQuery並執行查詢在父項應用程序(例如iPhone)上工作正常!但即使樣本在那裏,我也沒有新的樣本,但如果我將應用程序帶到背景並再次到達前景,我將獲得所有新的心率。 –
當然,關閉你的應用程序以獲取最新數據並不理想?我試圖暗示這個問題,並希望Apple能夠在iOS上進入HealthKit時獲得數據,而不需要像這樣的解決方法。 –