我正在开发一款应用程序,当您接近推广地点时发送通知。
我的问题是,当我切换到后台并退出应用程序时,我不希望定位服务在应用程序不工作时继续运行(但我希望它们在后台工作)。
我只看到了三个应用程序在关闭应用程序时关闭gps,我想知道他们是如何做到的,Facebook、Google 地图和 Apple 地图,而不是 Foursquare 或 FieldTrips ...
谢谢大家。
我正在开发一款应用程序,当您接近推广地点时发送通知。
我的问题是,当我切换到后台并退出应用程序时,我不希望定位服务在应用程序不工作时继续运行(但我希望它们在后台工作)。
我只看到了三个应用程序在关闭应用程序时关闭gps,我想知道他们是如何做到的,Facebook、Google 地图和 Apple 地图,而不是 Foursquare 或 FieldTrips ...
谢谢大家。
UIApplicationWillTerminateNotification
添加观察者,在那里启动locationManager,然后停止位置更新。[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillTerminate:)
name:UIApplicationWillTerminateNotification
object:nil];
- (void)applicationWillTerminate:(NSNotification *)notification {
//stop location updates
}
-(void)applicationWillTerminate:(UIApplication *)application
和 UIApplicationWillTerminateNotification
会被调用。 - Alex Peda由于@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;
接下来,您只需要在应用程序终止时停止位置服务即可...
谢谢您的回复。
@GuyS在这个主题中提供的解决方案应该可以工作。如果应用程序在后台运行并且我通过向上滑动快照关闭它,则会收到UIApplicationWillTerminateNotification
。请检查您是否正确使用NSNotificationCenter
(特别是添加和删除通知)。此外,请检查您订阅通知的对象在应用程序处于后台时是否仍然存在。
另一个类似的解决方案是将禁用GPS的代码放置在适当的UIApplicationDelegate
回调中,即您的AppDelegate
方法中。
- (void)applicationWillTerminate:(UIApplication *)application {
//stop location updates
}
AppDelegate
的applicationWillTerminate
方法中,您需要添加stopUpdatingLocation
或stopMonitoringSignificantLocationChanges
并将位置对象设置为nil
。希望这可以帮到您。 - ChintaN -Maddy- Ramani