简体   繁体   中英

How can I stop a background service in iOS after a certain period of time

I'm developing a Cordova project using this plugin: Cordova Plugin Background Geolocation to get GPS updates when my app is in background.

I would like to stop getting updates after 3 minutes the app is on background. I don't have the Objective-C skills to modify the plugin to achieve this.

I guess that there's a way to use a timer on Objective-C to stop the service after 3 minutes.

Can anyone help me with this?

UPDATE

The plugin has a stop method here .

You must modify your .plist file to indicate that you will be running tasks once the app has entered background...That being said, what you want might look something like this (all in AppDelegate)

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"Entered background");
    [self monitorLocation];
}

- (void)monitorLocation
{
[NSTimer scheduledTimerWithTimeInterval:180 //That's in seconds
    target:self
    selector:@selector(stopMonitoring)
    userInfo:nil
    repeats:NO];
    //Do whatever monitoring here

}

- (void)stopMonitoring
{
    //Stop monitoring location
}

 - (void)applicationWillEnterForeground:(UIApplication *)application {
    NSLog(@"app will enter foreground");
    [self stopMonitoring];
}

Try this solution, here you need to create global object of NSTimer and check whether NSTimer object is validate or not

-(void)applicationDidEnterBackground:(UIApplication *)application {

if ([objTimer isValid]) {
    [objTimer invalidate];
}else{
    objTimer = [NSTimer scheduledTimerWithTimeInterval:180 target:self selector:@selector(stopGPS:)  userInfo:nil repeats:NO];
}
objTimer = nil;}



- (void)stopGPS:(NSTimer *)timer {
// code for stoping GPS service.}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM