在后台运行iOS HTTP请求 [英] iOS HTTP request while in background

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

问题描述

当应用程序处于后台时,可以向PHP服务器发出HTTP异步请求吗?
应用程序是基于位置的应用程序,应该收集当前位置并每隔5(或其他值)分钟将坐标发送到服务器。即使应用程序在后台,我可以将http帖子发送到服务器吗?我读了很多关于这个的想法,但有些人告诉我们可以做到,有些人无法完成。

It is possible to make HTTP async requests to PHP server while the app being in background? The app is a location based one, and should gather current location and send the coordinates to server every 5(or other value) minutes. Can I make the http posts to the server even the app is in background? I read lot of thoughts about this, but some of them told that can be done, others that can't be done.

谢谢,

Alex。

推荐答案

它可以完成,但它不可靠,因为你要求操作系统有时间发送内容,它可以接受或拒绝你的请求。这就是我所拥有的(从某处偷来的东西):

It can be done but it is unreliable because you ask the OS for time to send something and it can accept or deny your request. This is what I have (stolen from somewhere on SO):

[...] //we get the new location from CLLocationManager somewhere here    
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
    isInBackground = YES;
}
if (isInBackground)
{
    [self sendBackgroundLocationToServer:newLocation];
}


- (void) sendBackgroundLocationToServer: (CLLocation *) lc
{
    UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
    bgTask = [[UIApplication sharedApplication]
         beginBackgroundTaskWithExpirationHandler:^{
             [[UIApplication sharedApplication] endBackgroundTask:bgTask];
    }];

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:2];
    [dictionary setObject:[NSNumber numberWithDouble:lc.coordinate.latitude] forKey:@"floLatitude"];
    [dictionary setObject:[NSNumber numberWithDouble:lc.coordinate.longitude] forKey:@"floLongitude"];
    // send to server with a synchronous request


    // AFTER ALL THE UPDATES, close the task
    if (bgTask != UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:bgTask];
    }
}

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

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