Question

Really confused about multitasking API in iOS, such as beginBackgroundTaskWithExpirationHandler etc.

For instance of recording video, when press button to start recording, we put

 if ([[UIDevice currentDevice] isMultitaskingSupported]) {
        [self setBackgroundRecordingID:[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{}]];
    }

when recording ends

if ([[UIDevice currentDevice] isMultitaskingSupported]) {
        [[UIApplication sharedApplication] endBackgroundTask:[self backgroundRecordingID]];
    }

so who can explain what is meaning of these. As you can see, when start recording, the block beginBackgroundTaskWithExpirationHandler is blank( just nothing to do ? ), and what is usage of those codes ?

Pretty much thanks for explaining.

Was it helpful?

Solution

Think of the expiration handler as any error handler. The system only allows the background application to use a limited amount of CPU time, so if you reach this limit, the background operation will be terminated, and your handler is called. Use it to clean up the internal state of your application.

OTHER TIPS

The purpose of these calls is to let your app go into the background without being suspended as it normally would be. They request that the system grant your app some extra time to live, even though it has been backgrounded.

The thing you want to do in the background is whatever lies between beginBackgroundTask... and endBackgroundTask:. The important thing is that having announced the start of your lengthy task with beginBackgroundTask... you must subsequently call endBackgroundTask: to let the system know you're done and it is now okay to suspend you. You must always balance these calls, no matter what route your code takes. Be sure to cover all situations!

The expiration handler is not the thing you want to do in the background; it is, as FX rightly says, an error handler. It will be called in a dire emergency where you've exceeded your background time limit (nominally ten minutes). If it is called, this means that the system is going to suspend you right now and you can't stop it.

You should never have an empty expiration handler! The reason is that if you hit your time limit and your expiration handler is actually called, if it does not call endBackgroundTask:, the system will not only forcibly suspend your app, it will kill your app! So, your expiration handler must always execute very quickly and must minimally include a call to endBackgroundTask:.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top