我正在开发一个应用程序,当你在推广的地方附近时发送通知。我的问题是,当我转到后台,然后退出应用程序时,我不想让定位服务在应用程序无法工作的情况下工作(但我希望它们在后台工作)。
我看到只有3个应用程序在应用程序关闭时关闭全球定位系统,我想知道他们是如何做到的,脸书,谷歌地图和苹果地图,不是Foursquare,不是FieldTrips……
谢谢大家。
发布于 2014-07-16 18:34:42
您可以在启动locationManager的位置添加UIApplicationWillTerminateNotification观察者,然后停止位置更新
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillTerminate:)
name:UIApplicationWillTerminateNotification
object:nil];接收到通知时要执行的方法
- (void)applicationWillTerminate:(NSNotification *)notification {
//stop location updates
}发布于 2014-07-16 22:38:19
我找到了我的问题的正确答案,因为@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中停止你的定位服务...
感谢您的回复。
发布于 2014-07-16 19:11:45
@GuyS在本主题中提供的解决方案应该是有效的。我正在获取UIApplicationWillTerminateNotification,以防应用程序在后台,然后我通过滑动快照来关闭它。请检查您是否正确使用NSNotificationCenter (特别是添加和删除通知)。另外,当应用程序在后台时,请检查您在通知中订阅的对象是否处于活动状态。
另一个类似的解决方案是将禁用GPS的代码放在AppDelegate方法的适当UIApplicationDelegate回调中。
- (void)applicationWillTerminate:(UIApplication *)application {
//stop location updates
}https://stackoverflow.com/questions/24778492
复制相似问题