Last active
December 28, 2015 10:39
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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