我想在每次收到位置更新时我的应用在后台时计算到目的地的路线。
但是,[MKDirections calculateDirectionsWithCompletionHandler]
是一个异步调用,因此我的问题是:如果在我的应用收到位置更新后需要超过5秒才完成,我的应用会被终止吗?您的建议是什么,以确保此请求有足够的时间完成?
答案 0 :(得分:1)
为了请求额外的时间让您的应用在后台运行以完成其任务(异步或非异常),您可以使用beginBackgroundTaskWithExpirationHandler:。
例如:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// If the application is in the background...
if([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive) {
// Create the beginBackgroundTaskWithExpirationHandler
// which will execute once your task is complete
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:application forKey:@"application"];
// Start a timer to keep the program alive for 180 seconds max
// (less if that's all that's necessary)
[NSTimer scheduledTimerWithTimeInterval:180 target:self selector:@selector(delayMethod:) userInfo:nil repeats:NO];
});
}
// ... the rest of your didUpdateToLocation: code ...
}
- (void)delayMethod:(NSTimer*)timer {
// End the background task you created with beginBackgroundTaskWithExpirationHandler
[[[timer userInfo] objectForKey:@"application"] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}