Search code examples
objective-cnstimervoipbackground-music

How do I make my App run an NSTimer in the background?


I'm making a benchmark App for test purposes ONLY. I am not intending this to go to the App Store.

What I need is my NSTimer to continue running on the background using a UIBackgroundTaskIdentifier, save data to a Core Data db and finally push the data to a server (I'm using Parse), after a certain time interval, of course.

So basically, I haven´t found any questions which apply to my specific case. I set my NSTimer like so:

    UIBackgroundTaskIdentifier bgTask;
UIApplication  *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask]; 
}];

self.timer = [NSTimer scheduledTimerWithTimeInterval:self.localInterval target:self selector:@selector(updateCoreData:) userInfo:nil repeats:YES];

the method updateCoreData simply calls the Core Data class and makes the necessary insertions.

I've read about VoIP and the Music playing part, but don't know exactly which one would apply best for my case, nor how to implement them.


Solution

  • I figured it out by myself, for anyone else with a similar problem, what I did was to first turn on the location update flag on your Info.plist file. To do this, you must add the Key called "Required Background Modes" on Xcode 4, then as a value, select "App registers for location updates"

    I have a timer declared like so in my .h file:

    NSTimer *silenceTimer;
    @property (nonatomic, retain) NSTimer *silenceTimer;
    

    Then on the .m file, I declared it like so:

    UIBackgroundTaskIdentifier bgTask;
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask]; 
    }];
    self.silenceTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self
    selector:@selector(startLocationServices) userInfo:nil repeats:YES];
    

    Finally, on the selector method, I made the following:

    -(void)startLocationServices {
        [locationManager startUpdatingLocation];
        [locationManager stopUpdatingLocation];
    }
    

    This will create a timer that starts and immediately stops location services after 5 minutes. This will be enough for the app to stay alive indefinately, unless you kill the process.