我們目前正在試圖讓HealthKit在後臺運行數據,以提供數據的步驟到我們的服務器時,應用程序被關閉。HealthKit(IOS)不會提供後臺(objC)
對於實驗目的,我們已經創建了一個全新的iOS項目在Xcode中,啓用HealhtKit和Compabilities所有背景模式。之後,我們幾乎可以運行代碼(詳見下文)。
所以會發生什麼首先是應用ofcourse請求的權限,這是我們授予。我們期望的是應用程序應該每隔一小時向服務器傳送步驟數據。但它沒有這樣做,它似乎應用程序無法做任何事情,當它不活躍。
的應用程序,只有當它被恢復或啓動,但不是在所有從背景(軟關閉/硬關閉)提供的數據
appdelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self setTypes];
return YES;
}
-(void) setTypes
{
self.healthStore = [[HKHealthStore alloc] init];
NSMutableSet* types = [[NSMutableSet alloc]init];
[types addObject:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]];
[self.healthStore requestAuthorizationToShareTypes: types
readTypes: types
completion:^(BOOL success, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
[self observeQuantityType];
[self enableBackgroundDeliveryForQuantityType];
});
}];
}
-(void)enableBackgroundDeliveryForQuantityType{
[self.healthStore enableBackgroundDeliveryForType: [HKQuantityType quantityTypeForIdentifier: HKQuantityTypeIdentifierStepCount] frequency:HKUpdateFrequencyImmediate withCompletion:^(BOOL success, NSError *error) {
}];
}
-(void) observeQuantityType{
HKSampleType *quantityType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKObserverQuery *query =
[[HKObserverQuery alloc]
initWithSampleType:quantityType
predicate:nil
updateHandler:^(HKObserverQuery *query,
HKObserverQueryCompletionHandler completionHandler,
NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (completionHandler) completionHandler();
[self getQuantityResult];
});
}];
[self.healthStore executeQuery:query];
}
-(void) getQuantityResult{
NSInteger limit = 0;
NSPredicate* predicate = nil;
NSString *endKey = HKSampleSortIdentifierEndDate;
NSSortDescriptor *endDate = [NSSortDescriptor sortDescriptorWithKey: endKey ascending: NO];
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType: [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount]
predicate: predicate
limit: limit
sortDescriptors: @[endDate]
resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
// sends the data using HTTP
[self sendData: [self resultAsNumber:results]];
});
}];
[self.healthStore executeQuery:query];
}
我把你的示例代碼和修改它,這樣它給了我一個本地通知,而不是將數據發送到服務器(因爲我沒有服務器)。它正在工作,但我做了其他一些更改,所以我不知道哪一個是必需的。我所做的更改是 - 擺脫主隊列上的所有dispatch_async。設置謂詞只提供今天的步驟(檢索所有步驟需要很長時間)。移動到'resultsHandler'結束調用completionHandler()在'getQuantityResult' - 所以它被調用一次全部處理完成 – Paulw11
嗨Paulw11,感謝您的回覆。你確定你在後臺得到結果,例如1小時後?我們得到的結果,但只有1-2分鐘,然後沒有。你呢? – Oakleaf
嗯,這很奇怪,我們可以讓它在模擬器中工作,但不在物理iPhone設備上。我們沒有線索,有誰知道要尋找什麼?由於它在模擬器中工作.. – Oakleaf