1

我正在为我们的办公室创建一个自定义应用程序。我希望这个应用程序每 5 分钟(左右)获取用户的位置,并通过 json 将其发送到我们的服务器。我让它工作,但它不会在后台运行超过 10 分钟(我可以说)。

我在必需的后台模式中添加了“用于位置更新的应用程序注册”。

我的代码在 AppDelegate 中,如下所示:

- (void)applicationDidBecomeActive:(UIApplication *)application
{

NSLog(@"Became active");

// Start location services
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 100.0f;
locationManager.delegate = self;

[locationManager stopMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];

}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{


BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
    isInBackground = YES;

}
NSLog(@"Location Manager isInBackground: %hhd", isInBackground);

if (isInBackground)
{
    [self sendBackgroundLocationToServer:newLocation];
}
else
{
    [self sendDataToServer:newLocation];
}

}


-(void) sendBackgroundLocationToServer:(CLLocation *)location
{

bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    [[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];

// Send the data
[self sendDataToServer:location];

if (bgTask != UIBackgroundTaskInvalid)
{
    [[UIApplication sharedApplication] endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}
}

-(void) sendDataToServer:(CLLocation *)newLocation
{
NSLog(@"Sending Data to Server");
// Get battery level
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
float batteryLevel = [[UIDevice currentDevice] batteryLevel];

float lat = newLocation.coordinate.latitude;
float lng = newLocation.coordinate.longitude;
NSLog(@"Accuracy: %f", newLocation.horizontalAccuracy);
NSString *userId = [[NSUserDefaults standardUserDefaults] stringForKey:@"userId"];
NSString *post = [[NSString alloc] initWithFormat:@"login_id=%@&latitude=%f&longitude=%f&speed=%f&course=%f&battery_level=%f&horizontal_accuracy=%f&vertical_accuracy=%f",
                  userId,
                  lat,
                  lng,
                  [newLocation speed],
                  [newLocation course],
                  batteryLevel,
                  newLocation.horizontalAccuracy,
                  newLocation.verticalAccuracy];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlstring = [NSString stringWithFormat:@"%@webservice/post_logins_location.php", kBaseURL];
[request setURL:[NSURL URLWithString:urlstring]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
jsonResults = [NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];
NSLog(@"GPS Send results: %@", jsonResults);

_lastSentUpdateAt = [NSDate date];
}

我还尝试使用 startMonitoringSignificantLocationChanges 并完全删除 _lastSentUpdateAt。但是我仍然得到相同的结果。我现在的问题是,json可以在10分钟后从后台发送数据吗?现在我的手机已经运行了一个多小时,并且我的应用程序的定位服务图标仍然处于活动状态。但是,我没有看到任何数据通过更新到达我的服务器。一旦我真正打开我的应用程序,它确实会收到更新,这让我相信在后台发送数据存在问题。还是有其他事情发生?

4

1 回答 1

2

阅读文档并观看与“注册重要位置更新”相关的 WWDC 演示文稿。他们对官方推荐的方法进行了改进和更改,同时谨慎使用功耗。

具体来说,无法以您指定的时间间隔获取背景位置。重要的位置更新由操作系统自行决定触发,并受许多超出您的应用控制范围的因素的影响。

如果您要做的只是防止应用程序在后台终止,则需要在应用程序的 plist 中声明这种后台模式。我认为它在 Xcode 中的“信息”下,在“应用程序注册位置更新”下。

于 2013-09-17T18:11:57.477 回答