当应用程序进入后台时,我需要不断获取用户的位置更新,正如我在 Apple 的文档中发现的那样,这是允许实现的长期运行的后台任务之一。当通知位置更新时,我还需要进行一些处理和网络调用以向服务器发送一些信息。概括地说,我想做的是这样的:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Background task
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"Background time remaining: %f seconds (%d mins)",
[[UIApplication sharedApplication] backgroundTimeRemaining],
(int)([[UIApplication sharedApplication] backgroundTimeRemaining] / 60));
// Need to get data from database here
// Finished
if (bgTask != UIBackgroundTaskInvalid) {
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
// Start location manager
locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager locationServicesEnabled]) {
locationManager.delegate = self;
locationManager.distanceFilter = 20;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Want to perform some data processing here, including concurrent tasks
// and several network calls to get and send data to server
[self locationProcessingCompleted];
});
}
- (void)locationProcessingCompleted
{
// Check results. If needed, some more data processing and several network
// calls to send data to server
// Close background task
if (bgTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}
我没有找到任何关于位置服务的长期运行后台任务的代码示例,对此我有几个问题:
a) 是否有必要在dispatch_async
队列中执行所有后台代码?换句话说,是否所有代码都applicationDidEnterBackground:
异步执行,包括位置管理器设置?
b)[[UIApplication sharedApplication] backgroundTimeRemaining]
返回一个很长的值。这个时间不应该是10分钟左右吧?
c)我想做:执行初始有限长度任务,开始位置更新,然后每次didUpdateToLocation:
触发时执行一些其他有限长度任务。我已经设置了in的location
值。我的方法正确吗?我是否会无限期地更新位置,然后我是否可以在每次收到更新时执行少于 10 分钟的有限长度任务?UIBackgroundModes
Info.plist
拜托,我需要帮助解决这个问题。提前致谢