Question

I have a background task that stop a streamer after 30 minutes as follows:

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


bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    [[UIApplication sharedApplication] endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    while ([[NSDate date] timeIntervalSinceDate:[[NSUserDefaults standardUserDefaults]objectForKey:@"date"]]<30) {
        NSLog(@"<30");

         [NSThread sleepForTimeInterval:1];


     }
    NSLog(@"Stop");
    [main stopStreaming];


 });
}

but the problem is when the user Did Enter Background the bgTask called again, thats mean if the user entered the background 10 times he will have 10 back ground UIBackgroundTaskIdentifier

That cause the streamer playing badly and the NSLog(@"<30"); get called more than one time at the same second.

Please Advice.

Was it helpful?

Solution

You'll have to keep track of the background tasks you have started and make sure you don't do the work of previous tasks when a new task is started. You can do this easily by keeping an NSInteger around in your app delegate and incrementing it for each time.

But the easier way is just this: (in place of your dispatch_async call)

SEL methodSelector = @selector(doThisAfter30Seconds);
[[self class] cancelPreviousPerformRequestsWithTarget:self selector:methodSelector object:nil];
[self performSelector:methodSelector  withObject:nil afterDelay:30];

This will set a timer for 30 seconds and make sure the previous timers are not run. Then just implement - (void)doThisAfter30Seconds to do whatever you want.

(You will probably want to check in doThisAfter30Seconds that the task is still in the background, or manually remove the timer with cancelPreviousPerformRequestsWithTarget:... in applicationWillEnterForeground:.)

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