在后台运行iOS HTTP请求

Ale*_*cus 16 iphone objective-c core-location

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

谢谢,

亚历克斯.

vak*_*kio 21

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

[...] //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];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 那个'isInBackground`是完全没必要的. (3认同)
  • 非常感谢,我宣布您为年度开发者:)。所以,基本上,它可能会在某些时候工作,而其他人则不会,这取决于操作系统。 (2认同)