我们正在尝试让HealthKit在后台工作,以便在应用程序关闭时将步骤数据提供给我们的服务器.
为了实验目的,我们在XCode中创建了一个全新的iOS项目,启用了HealhtKit和Compabilities中的所有后台模式.之后,我们几乎运行代码(见下文).
那么首先发生的是应用程序要求我们授予的权限.我们期望的是应用程序应该每小时将数据传递到服务器.但它没有这样做,似乎应用程序不能做任何事情,当它不活跃.
该应用程序仅在恢复或启动时才提供数据,但根本不提供背景信息(软关闭/硬关闭)
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];
- }
解决方法
我看到可能在AppDelegate中引起问题的内容,特别是这一行:
- [[NSURLConnection alloc] initWithRequest:request delegate:self];
这是创建一个NSURLConnection,但不启动它.尝试改为:
- NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
- [connection start];
编辑:再次查看文档后
他们建议在您的应用程序中设置观察器查询didFinishLaunchingWithOptions:方法.在上面的代码中,将HKObserverQuery设置在授权处理程序中,该处理程序在随机的后台队列中调用.尝试进行此更改以在主线程上进行设置:
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
- [self setTypes];
- [self observeQuantityType];
- return YES;
- }