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

标签 ios objective-c mapkit cllocationmanager

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

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

相关文章:

ios - 快速调用电话号码

ios - 如何在 map 上的所有注释图钉上显示不同的图像?

ios - BNHtmlPdfKit PDF 中的页眉和页脚

iphone - 缩放以适合所有注释的区域 - 最终在注释之间放大

ios - 您应该如何将推送 token 数据转换为字符串以供查看/调试/记录/放入 http 以发送到服务器?

iphone - 如何在 iPhone 上扩展键盘渐变?

ios - How to indent documentation in appledoc/HeaderDoc(关于带参数的 block 的文档)

iphone - 根据用户在 map 中跟随的方向旋转图像

ios - 更改 MKAnnotation 引脚颜色

iphone - iOS-FBConnect - 如果他们的委托(delegate)被释放,请求结果会使应用程序崩溃