iOS后台任务使用NSURLSessionDataTask [英] iOS background task using NSURLSessionDataTask

查看:1041
本文介绍了iOS后台任务使用NSURLSessionDataTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有飞行搜索功能,这需要很长时间才能获取数据(超过25秒)。如果应用程序进入后台或进入睡眠模式,互联网连接将断开连接。

I have flight search feature in my application which is taking too long to get the data (more than 25 seconds). if application goes background or went to sleep mode, internet connection get disconnected.

我已经使用苹果示例编写了以下逻辑,以使api请求继续运行,即使应用程序转到背景,但它不起作用。

I have written below logic using apple example to make api request keep going even though if app goes to background but it's not working.

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;
}

当应用程序处于前台时,一切正常,但只要我将应用程序放在背景低于错误消息。

Everything works fine when application is in foreground but as soon as I put application on background getting below error message.


错误已完成:与后台传输服务的连接丢失

Completed with error: Lost connection to background transfer service


推荐答案

您不能将数据任务用于后台传输。这些必须使用下载任务完成:

You cannot use data tasks for background transfers. Those must be done using download tasks:


下载任务以文件的形式检索数据,并支持应用程序未运行时
后台下载。

Download tasks retrieve data in the form of a file, and support background downloads while the app is not running.

这在Apple的文档

另请务必查看他们的后台转移注意事项


使用后台会话,因为实际转移是由
一个单独的流程,因为重启你的应用程序的过程是
相对昂贵,有些功能不可用,导致
foll由于限制...

With background sessions, because the actual transfer is performed by a separate process and because restarting your app’s process is relatively expensive, a few features are unavailable, resulting in the following limitations...

这里的关键是它在一个单独的进程中运行,无法访问你保存在内存中的数据。它必须通过文件进行路由。

The key here is that it's running in a separate process which cannot access the data you keep in memory. It must be routed through a file.

我在(长)博客文章

这篇关于iOS后台任务使用NSURLSessionDataTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆