为了实验目的,我们在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;}
HKObserverQuery Reference
总结以上是内存溢出为你收集整理的HealthKit(iOS)不会在后台传递数据(objC)全部内容,希望文章能够帮你解决HealthKit(iOS)不会在后台传递数据(objC)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)