我正在构建一个具有区域监控功能的应用程序。它在前台工作正常,但一旦应用程序在后台发送,它的行为就不会按预期进行:它确实调用 didEnter 和 didExit,但一旦开始执行回调,它就会停止。在这些回调方法中,我需要轮询服务器并保留 didExitRegion 和/或 didEnterRegion 状态。一旦我再次将应用程序置于前台,任何排队的请求就会开始并完成。 任何想法? 我在 iphone 4 上使用 ios5.1 和 ios6
最佳答案
当您在后台接到电话时
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
(或...退出)
只需设置服务器调用所需的任何内容(变量、服务器的有效负载等)。 在实际发送开始之前
self.bgTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:self.bgTaskId];
self.bgTaskId = UIBackgroundTaskInvalid;
somelogger(@"ran out of time for background task");
// remember that we failed for the next time the app comes to the foreground
}];
然后使用您选择的 HTTP 框架进行实际发送,并在完成处理程序中使用
重置后台任务[[UIApplication sharedApplication] endBackgroundTask:self.bgTaskId];
使用 AFNetworking 的示例:
[self.httpClient postPath:@"state" parameters:@{@"abc": abc, @"value": val, @"h": h, @"app":myAppName , @"version": myAppVersion }
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (operation.response.statusCode != 200) {
DDLogVerbose(@"response was not 200. error: %i", operation.response.statusCode);
} else {
DDLogVerbose(@"success");
}
[[UIApplication sharedApplication] endBackgroundTask:self.bgTaskId];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogVerbose(@"request error %@, current retry count %d", error, retryCount );
// start our own retry mechanism
if (retryCount < MAX_RETRIES) {
retryCount++;
double delayInSeconds = RETRY_INTERVAL * (1 + (double)retryCount/10);
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// try again
});
} else {
// final
[[UIApplication sharedApplication] endBackgroundTask:self.bgTaskId];
// remember failure when app comes back to foreground
}
}];
我正在使用
@property (assign, nonatomic) UIBackgroundTaskIdentifier bgTaskId;
存储背景标识符。
关于iOS后台区域位置更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13829963/