在后台运行iOS HTTP请求

时间:2012-08-08 12:28:31

标签: iphone objective-c core-location

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

谢谢,

亚历。

2 个答案:

答案 0 :(得分:19)

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

[...] //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];
    }
}

答案 1 :(得分:3)

这些链接将帮助您...

iphone - Connecting to server in background