Welkin's Secret Garden

Black Tech -- Keep Running in the Background

It is common sense that app on iOS will keep running in the background for 10 minutes except for tasks like downloading or playing music, but I accidentally find a trick, letting the app keep running as long as you want.

1. Declare in info.plist

First, add an item Required background modes : App plays audio or streams audio/video using AirPlay to the info.plist .

2. Ask for Background time in AppDelegate

1
2
3
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
}

3. Add a timer

Add a timer at wherever that will be called and set its duraton to 60s.

1
_timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(requestBackground) userInfo:nil repeats:YES];

Check the remaining time in its callback.

1
2
3
4
5
6
- (void)requestBackground {
if (UIApplication.sharedApplication.backgroundTimeRemaining < 61.0) {
[[AudioTool sharedInstance] playSound];
[UIApplication.sharedApplication beginBackgroundTaskWithExpirationHandler:nil];
}
}

If the remaining time is less than 61s, push the task to foreground by playing a soundless audio and ask for background time again. This is for the reason that the action of asking can not be executed in background.

For the audio, we need to set

1
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error];

to let it not to conflict with other audio played by user and give it the ablity to process even when the screen is locked.

All right, to be honest, I do not approve of this way as well. Through Practice, the power consumption increases significantly by this way, making me swipe it up on it after pressing the home button. What is worse, I believe this trick will not be permitted when reviewed by App Store.