我的应用程序中有一个航班搜索功能,获取数据的时间太长了(超过25秒)。如果应用程序进入后台或进入睡眠模式,互联网连接将断开。
我使用苹果示例编写了以下逻辑,使API请求在应用程序进入后台时仍然继续进行,但它没有起作用。
self.session = [self backgroundSession];
self.mutableData = [NSMutableData data];
NSURL *downloadURL = [NSURL URLWithString:@"http://jsonplaceholder.typicode.com/photos"];
NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
self.dataTask = [self.session dataTaskWithRequest:request];
[self.dataTask resume];
- (NSURLSession *)backgroundSession
{
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession"];
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
});
return session;
}
以下是代理方法:
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
NSLog(@"response: %@", response.debugDescription);
NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;
if (completionHandler) {
completionHandler(disposition);
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
[self.mutableData appendData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
BLog();
if (error == nil)
{
NSData *data = nil;
if (self.mutableData) {
data = [self.mutableData copy];
self.mutableData = nil;
}
NSError* error;
NSArray* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (!json) {
NSLog(@"Error parsing JSON: %@", error);
} else {
NSLog(@"Data: %@", json);
}
}
else
{
NSLog(@"Task: %@ completed with error: %@", task, [error localizedDescription]);
}
double progress = (double)task.countOfBytesReceived / (double)task.countOfBytesExpectedToReceive;
dispatch_async(dispatch_get_main_queue(), ^{
self.progressView.progress = progress;
});
self.dataTask =nil;
}
当应用程序在前台时,一切都正常,但是一旦将应用程序放到后台,就会收到以下错误消息。
完成出错:与后台传输服务失去连接