21

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

谢谢,

亚历克斯。

4

2 回答 2

24

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

[...] //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];
    }
}
于 2012-08-08T12:44:33.757 回答
4

这些链接将帮助您...

iphone - 在后台连接到服务器

于 2012-08-08T12:51:31.063 回答