iOS后台位置不发送http请求 [英] iOS background Location not sending http request

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

问题描述

我的应用需要在后台跟踪用户位置,但无法发送获取请求。当应用程序到达前台时,http请求会立即发送。我正在使用RestKit来处理我的所有网络请求,我跟着本教程设置我的后台位置服务。
在我的applicationDidEnterBackground中

My app needs to track the users location in the background but it is failing to send a 'get' request. The http request gets sent immediately when the app comes to the foreground. I am using RestKit for all my network requests and I followed this tutorial to setup my background locations service. In my applicationDidEnterBackground

-(void)applicationDidEnterBackground:(UIApplication *)application
{
    self.bgLocationManager = [[CLLocationManager alloc] init];
    self.bgLocationManager.delegate = self;
    [self.bgLocationManager startMonitoringSignificantLocationChanges];
    NSLog(@"Entered Background");
}

我在我的applicationDidBecomeActive委托中停止监控SignignantLocationChange

and I stopMonitoringSignificantLocationChange in my applicationDidBecomeActive delegate

这是我的locationManager委托,我接受新的更新位置并发送到我的服务器

This is my locationManager delegate where I accept the new updated location and send to my server

-(void) locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
           fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"I am in the background");
    bgTask = [[UIApplication sharedApplication]
                beginBackgroundTaskWithExpirationHandler:
                ^{
                      [[UIApplication sharedApplication] endBackgroundTask:bgTask];
                 }];
                 // ANY CODE WE PUT HERE IS OUR BACKGROUND TASK

    NSString *currentLatitude = [[NSString alloc]
                                  initWithFormat:@"%g",
                                  newLocation.coordinate.latitude];
    NSString *currentLongitude = [[NSString alloc]
                                   initWithFormat:@"%g",
                                   newLocation.coordinate.longitude];
    NSString *webToken = [[NSUserDefaults standardUserDefaults] stringForKey:@"userWebToken"];
    NSLog(@"I am in the bgTask, my lat %@", currentLatitude);

    NSDictionary *queryParams;
    queryParams = [NSDictionary dictionaryWithObjectsAndKeys:webToken, @"auth_token",  currentLongitude, @"lng", currentLatitude, @"lat", nil];
    RKRequest* request = [[RKClient sharedClient] post:@"/api/locations/background_update" params:queryParams delegate:self];
    //default is RKRequestBackgroundPolicyNone
    request.backgroundPolicy = RKRequestBackgroundPolicyContinue;

    // AFTER ALL THE UPDATES, close the task

    if (bgTask != UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }
}

网络请求按计划运行但不会得到在后台调用。我还需要其他步骤吗?在我的info.plist中,我将所需的背景模式键和位置服务作为值。

The network requests works as planned but it will not get called in the background. Is there any additional steps I need? In my info.plist I have the Required Background modes key and location-services as the value.

编辑

我还提到这个过去的答案。我通过在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


尝试用库存同步NSURLConnection替换你的restKit调用吗? - dklt Sep 20

Have your try replacing your restKit calls with a stock synchronous NSURLConnection? – dklt Sep 20

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

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