简体   繁体   English

在后台运行iOS HTTP请求

[英]iOS HTTP request while in background

It is possible to make HTTP async requests to PHP server while the app being in background? 当应用程序处于后台时,可以向PHP服务器发出HTTP异步请求吗? The app is a location based one, and should gather current location and send the coordinates to server every 5(or other value) minutes. 该应用程序是基于位置的应用程序,应该收集当前位置并每隔5(或其他值)分钟将坐标发送到服务器。 Can I make the http posts to the server even the app is in background? 即使应用程序在后台,我可以将http帖子发送到服务器吗? I read lot of thoughts about this, but some of them told that can be done, others that can't be done. 我读了很多关于这方面的想法,但有些人告诉我们可以做到,有些则无法完成。

Thanks, 谢谢,

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

These links will help you out... 这些链接将帮助您...

iphone - Connecting to server in background iphone - 在后台连接到服务器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM