Run app for more than 10 minutes in background

Run app for more than 10 minutes in background

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 {
[[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;
}
}

你可能感兴趣的:(Run app for more than 10 minutes in background)