0
我想在我的應用程序每次收到位置更新時在後臺計算到目的地的路線。MKDirections在應用程序處於後臺時計算方向
但是,[MKDirections calculateDirectionsWithCompletionHandler]
是一個異步調用,因此我的問題是:如果我的應用程序接收到位置更新後需要超過5秒才能完成,我的應用程序會終止嗎?你有什麼建議來確保這個請求有足夠的時間完成?
我想在我的應用程序每次收到位置更新時在後臺計算到目的地的路線。MKDirections在應用程序處於後臺時計算方向
但是,[MKDirections calculateDirectionsWithCompletionHandler]
是一個異步調用,因此我的問題是:如果我的應用程序接收到位置更新後需要超過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;
}
咦? Asynchronous = background – 2015-01-09 19:09:50
@LyndseyScott是的,但我理解這一點的方式是,當請求額外的時間時,你所做的所有事情都需要同步。這至少是我讀過的所有教程中所獲得的。 **編輯:**我理解你的困惑。我的意思是,我的應用程序實際上是後臺,終止等。 – Aleksander 2015-01-09 19:14:21
哦,gotcha。您可以請求最多幾分鐘完成該任務:https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072 -CH4-SW3 – 2015-01-09 19:20:16