【问题标题】:MKDirections calculate directions when app is in the background当应用程序在后台时,MKDirections 计算方向
【发布时间】:2015-01-09 19:05:01
【问题描述】:

每当我的应用程序在后台接收位置更新时,我想计算前往目的地的路线。

但是,[MKDirections calculateDirectionsWithCompletionHandler] 是一个异步调用,因此我的问题是:如果在我的应用收到位置更新后需要超过 5 秒才能完成,我的应用会被终止吗?你有什么建议来确保这个请求有足够的时间来完成?

【问题讨论】:

  • 嗯?异步 = 背景
  • @LyndseyScott 是的,但我的理解是,在请求额外时间时,您所做的所有事情都需要同步。这至少是我从我读过的所有教程中得到的。 编辑:我理解你的困惑。我的意思是我的应用实际上是后台运行、终止等。
  • 哦,明白了。您最多可以请求几分钟来完成任务:developer.apple.com/library/ios/documentation/iPhone/Conceptual/…
  • @LyndseyScott 但这样做时不是所有任务都必须同步吗?
  • 不,我已经将此方法用于异步任务。我现在正在查看旧代码以了解具体细节...

标签: ios objective-c mapkit cllocationmanager


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 2020-06-20
    • 2019-05-30
    相关资源
    最近更新 更多