当你在后台被调用时
- (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;
存储背景标识符。
整个机制解释在http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW28