当我的应用程序每次收到位置更新时都在后台运行时,我想计算到达目的地的路线。
但是,[MKDirectionscalculateDirectionsWithCompletionHandler]
是一个异步调用,因此我的问题是:如果在我的应用程序收到位置更新后需要超过 5 秒才能完成,我的应用程序是否会终止?为了确保此请求有足够的时间完成,您有何建议?
最佳答案
为了请求额外的时间让您的应用程序在后台运行以完成其任务(异步或非异步),您可以使用 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;
}
关于ios - MKDirections 在应用程序处于后台时计算方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27867449/