当应用程序在后台运行时,是否可以对PHP服务器进行异步的HTTP请求?
这个应用程序是基于位置的,需要每隔5分钟(或其他值)收集当前位置并将坐标发送到服务器。即使应用程序在后台运行,我也可以向服务器发出HTTP POST请求吗?我阅读了很多关于此的思路,但有些人说可以做到,有些人则说不行。
谢谢,
Alex.
当应用程序在后台运行时,是否可以对PHP服务器进行异步的HTTP请求?
这个应用程序是基于位置的,需要每隔5分钟(或其他值)收集当前位置并将坐标发送到服务器。即使应用程序在后台运行,我也可以向服务器发出HTTP POST请求吗?我阅读了很多关于此的思路,但有些人说可以做到,有些人则说不行。
谢谢,
Alex.
这是可以做到的,但是不可靠,因为你向操作系统请求发送某些东西的时间,操作系统可以接受或拒绝你的请求。以下是我从stackoverflow某处盗取的代码:
[...] //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];
}
}
isInBackground
完全不必要。 - 2rs2ts以下链接可以帮助您解决问题...