MKDirections 在应用程序处于后台时计算方向

MKDirections calculate directions when app is in the background

我想在我的应用程序每次收到位置更新时都在后台时计算到目的地的路线。

但是,[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;
}