当应用程序终止时停止位置更新。

3

我正在开发一款应用程序,当您接近推广地点时发送通知。

我的问题是,当我切换到后台并退出应用程序时,我不希望定位服务在应用程序不工作时继续运行(但我希望它们在后台工作)。

我只看到了三个应用程序在关闭应用程序时关闭gps,我想知道他们是如何做到的,Facebook、Google 地图和 Apple 地图,而不是 Foursquare 或 FieldTrips ...

谢谢大家。


根据我的理解,您想在应用程序退出时删除位置信息,但在后台运行时保留位置信息。为此,在AppDelegateapplicationWillTerminate方法中,您需要添加stopUpdatingLocationstopMonitoringSignificantLocationChanges并将位置对象设置为nil。希望这可以帮到您。 - ChintaN -Maddy- Ramani
很抱歉,这并不容易……当您关闭应用程序并在后台时,它不会触发applicationWillTerminate... - Javier Peigneux
哦,现在我能理解你的问题了。 :) - ChintaN -Maddy- Ramani
3个回答

1
你可以为UIApplicationWillTerminateNotification添加观察者,在那里启动locationManager,然后停止位置更新。
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillTerminate:)
                                                 name:UIApplicationWillTerminateNotification
                                               object:nil];

收到通知时执行的方法
- (void)applicationWillTerminate:(NSNotification *)notification {
//stop location updates
}

我尝试了,但不幸的是这并不容易...当你关闭应用程序并处于后台时,它没有发送那个通知。 - Javier Peigneux
@JavierPeigneux 你是怎么测试的?我发现当其他应用在前台时,我们通过向上滑动快照关闭应用程序时,-(void)applicationWillTerminate:(UIApplication *)applicationUIApplicationWillTerminateNotification 会被调用。 - Alex Peda
@AlexPeda 问题在于当应用程序处于后台时,然后通过向上滑动快照关闭它...我使用日志、断点测试了它,并且我有停止 GPS 的代码,在其余的代码中它是有效的,但在那里从来没有起作用... - Javier Peigneux
我已经在主题中发布了新的答案。希望它能有所帮助。祝好运 :) - Alex Peda
看一下这篇帖子:https://dev59.com/V1_Va4cB1Zd3GeqPXuDW,原帖的第二个问题是你所描述的问题吗?如果是的话,被接受的答案应该能解决它。 - Guy S

1

由于@GuyS的第二篇帖子,我找到了正确的答案:

在您的AppDelegate.m中添加applicationDidEnterBackground

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UIApplication *app = [UIApplication sharedApplication];
    if ([app respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]) {
        bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
            // Synchronize the cleanup call on the main thread in case
            // the task actually finishes at around the same time.
            dispatch_async(dispatch_get_main_queue(), ^{
                if (bgTask != UIBackgroundTaskInvalid)
                {
                    [app endBackgroundTask:bgTask];
                    bgTask = UIBackgroundTaskInvalid;
                }
            });
        }];
    } 
}

并声明该变量:

UIBackgroundTaskIdentifier bgTask;

接下来,您只需要在应用程序终止时停止位置服务即可...

谢谢您的回复。


这应该是一个被接受的答案,它解决了当应用程序在后台时调用applicationWillTerminate的问题。 - Amro Younes

0

@GuyS在这个主题中提供的解决方案应该可以工作。如果应用程序在后台运行并且我通过向上滑动快照关闭它,则会收到UIApplicationWillTerminateNotification。请检查您是否正确使用NSNotificationCenter(特别是添加和删除通知)。此外,请检查您订阅通知的对象在应用程序处于后台时是否仍然存在。

另一个类似的解决方案是将禁用GPS的代码放置在适当的UIApplicationDelegate回调中,即您的AppDelegate方法中。

- (void)applicationWillTerminate:(UIApplication *)application {
//stop location updates
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接