Stop location updates when app terminate

邮差的信 提交于 2019-12-14 01:29:50

问题


I'm developing an app which sends notifications when you are nearby of promoted places. My problem is when I go to background and then I quit the app, I don't want the location services working when the app doesn't work (but I want them to work in background).

I saw only 3 apps which close the gps when the app is closed and I want to know how they did that, Facebook, Google Maps and Apple Maps, not Foursquare, not FieldTrips...

Thank you everybody.


回答1:


you can add an observer for UIApplicationWillTerminateNotification where you start locationManager and than stop location updates

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillTerminate:)
                                                 name:UIApplicationWillTerminateNotification
                                               object:nil];

method to perform when you receive the notification

- (void)applicationWillTerminate:(NSNotification *)notification {
//stop location updates
}



回答2:


I found the correct answer to my question becouse of @GuyS second post:

Adding that in your 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;
                }
            });
        }];
    } 
}

And declaring that variable:

UIBackgroundTaskIdentifier bgTask;

After that you only have to stop your location services in applicationWillTerminate...

Thank you for your replies.




回答3:


The solution provided by @GuyS in this topic should work. I'm getting the UIApplicationWillTerminateNotification in case the app is in background and then I close it by swiping up the snapshot. Please check whether you work correctly with NSNotificationCenter (especially adding and removing notification). Plus, please check the object you subscribed on the notification is alive when the app is in background.

Another similar solution is to place the code that disables GPS in appropriate UIApplicationDelegate callback in your AppDelegate method.

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


来源:https://stackoverflow.com/questions/24778492/stop-location-updates-when-app-terminate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!