-->

How to keep my app longer than 10 min. in the back

2020-07-13 09:53发布

问题:

I know that in iOS, background apps can only be running

  • Finite-length tasks (10 min)
  • Location updates
  • VoIP
  • Audio

Is there a way for my application to avoid being terminated after being 10 min. in the background? I will not be submitting my app to the app store, so everything is allowed (private frameworks, using the gps even if I don't need it) I know apple does not recommend this, but it is just for monitoring purposes. I need it to be running without a limit.

I explored several possibilities including the VoIP , but it only gives me 30 seconds every 10 minutes, which is not enough. I also read this post: iPhone - Backgrounding to poll for events in which JackPearse specified a way to "revive" the 10 minute finite-length task using the VoIP 30 second task. But I don't want my task to start and end every 10 minutes, it must run continuosly. I also tried his UPDATE2, but it's not working for me. I even tried intercepting the UIEvent with GSEvent.type 2012, which seemed to be the one ending my background task, but no luck. Strangely, my background task is never ended when I have Xcode opened and debugging, but when I don't (test the simulator alone) it ends after 10 minutes.

回答1:

I have already tried some way(nsrunloop,*performselectoronmainthread*) like that.It's works well in simulator (not in device because apple crashes automatically after sometimes) when the app goes to background.

status is a BOOL variable.

- (void)applicationDidEnterBackground:(UIApplication *)application {

    while (!**status**) {
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:60.0]];
        [self goBackground];
    }
}


回答2:

I found out how to keep my Application in the background for longer than 10 minutes by continuously playing a song in the background. On the AppDidFinishLauching:

[[AVAudioSession sharedInstance] setActive:YES error:&error];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
NSURL *url = [NSURL fileURLWithPath:...]; //Song URL
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

player.numberOfLoops = -1;
[player play];

In the AppDidEnterBackground you can perform a selector in background, which can last forever. The App will not be interrupted, you can check UIApplication backgroundtimeRemaining and see it never decreases.

Of course, declare the app as a background audio App in the plist.