应用程序终止时停止位置更新
我正在开发一个应用程序,当你在附近的升级地点发送通知。 我的问题是,当我去背景,然后我退出了应用程序,我不希望位置服务工作时,应用程序不工作(但我希望他们在后台工作)。
我只看到3个closures应用程序closuresGPS的应用程序,我想知道他们是如何做到这一点,Facebook,谷歌地图和苹果地图,而不是Foursquare,而不是FieldTrips …
谢谢大家。
您可以在启动locationManager的位置添加UIApplicationWillTerminateNotification
的观察者,并停止位置更新
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
方法在您收到通知时执行
- (void)applicationWillTerminate:(NSNotification *)notification { //stop location updates }
我发现我的问题正确的答案,因为@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; } }); }]; } }
并声明这个variables:
UIBackgroundTaskIdentifier bgTask;
之后,你只需要停止applicationWillTerminate你的位置服务…
谢谢您的回复。
@GuyS在这个主题中提供的解决scheme应该可以工作。 我得到了UIApplicationWillTerminateNotification
,以防应用程序在后台,然后通过刷新快照来closures它。 请检查您是否正确使用NSNotificationCenter
(尤其是添加和删除通知)。 另外,当应用程序处于后台时,请检查您订阅的对象是否处于活动状态。
另一个类似的解决scheme是在您的AppDelegate
方法中将禁用GPS的代码放入适当的UIApplicationDelegate
callback中。
- (void)applicationWillTerminate:(UIApplication *)application { //stop location updates }