本文介绍了iOS后台位置不发送http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用需要在后台跟踪用户位置,但无法发送获取请求。当应用程序到达前台时,http请求会立即发送。我正在使用RestKit来处理我的所有网络请求,我跟着。我通过在didUpdateToLocation调用中放置日志来运行一些测试,并且它们都被调用但是没有发送'get'请求。相反,当我最终将应用程序启动到前台时,它发送了所有构建的网络请求(超过10个)。

I also referred to this past SO answer. I ran some tests with putting logs throughout the didUpdateToLocation call and they were all called but the 'get' request was not sent. Instead when I finally launch the app to the foreground it sent all the built of network requests (over 10).

编辑(2)
我添加了RKRequestBackgroundPolicyContinue到我的请求,但它没有改变我的结果。 (正如您所见,在后台上传/下载restkit)。我看到Restkit初始化主机,但在应用程序变为活动状态之前无法发送请求。

EDIT (2)I added RKRequestBackgroundPolicyContinue to my request but it did not change my results. (As you can see here in the background upload/download for restkit). I see Restkit initialize the host but fails to send the request until the app becomes active.

ANSWER

RestKit必须做一些在后台禁止的事情。使用NSURLRequest非常有效。

RestKit must be doing something that is prohibited in the background. Using an NSURLRequest works perfectly.

NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/api/locations/background_update"]];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:jsonData];

NSHTTPURLResponse  *response = nil;
[NSURLConnection sendSynchronousRequest:urlRequest
                      returningResponse:&response
                                  error:&error];

使用同步请求是好的,因为没有UI可以破坏后台任务

It is fine to use a synchronous request since there is no UI to disrupt with background tasks

推荐答案

重新创建原始建议作为答案

Re-creating original suggestion as an answer

这篇关于iOS后台位置不发送http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:06
查看更多