Skip to content

Instantly share code, notes, and snippets.

@rismay
Last active December 28, 2015 10:39
Show Gist options
  • Save rismay/7488145 to your computer and use it in GitHub Desktop.
Save rismay/7488145 to your computer and use it in GitHub Desktop.
This code makes your iOS app run indefinitely in the background. Copy and paste the below methods into a singleton / manager which handles the tasks you need to perform in the background.
// @interface
// Declare Private property
@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;
//@end
// ...
// Copy into
//@implementation
- (void)setupBackgrounding {
self.backgroundTask = UIBackgroundTaskInvalid;
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appBackgrounding:)
name: UIApplicationDidEnterBackgroundNotification
object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appForegrounding:)
name: UIApplicationWillEnterForegroundNotification
object: nil];
}
- (void)appBackgrounding: (NSNotification *)notification {
[self keepAlive];
}
- (void) keepAlive {
self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
[self keepAlive];
}];
}
- (void)appForegrounding: (NSNotification *)notification {
if (self.backgroundTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment