how can I automatically stop all background tasks when app is coming in foreground state
<p>i am using following code</p>

<pre><code>#if __IPHONE_OS_VERSION_MAX_ALLOWED &gt;= 40000
if ([[UIApplication sharedApplication]
     respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)])
{
    UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication]
                                         beginBackgroundTaskWithExpirationHandler:^{}];

    // Perform work that should be allowed to continue in background
    [self changeCounter];
    //[NSThread detachNewThreadSelector:@selector(changeCounter) toTarget:self withObject:_viewController];

    [[UIApplication sharedApplication] endBackgroundTask:bgTask];
}
#endif
</code></pre>

<p>changeCounter contains loops which may end after some time .But before ending the loop if app comes in foreground then i can see only black screen untill loop finishes.
So how can I stop all tasks as app comes in foreground  </p>

<p>this is  code for changeCounter</p>

<pre><code> -(void)changeCounter{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

while(back==1.0f){
    NSLog(@"loop is runnig");
    [NSThread sleepForTimeInterval:1.0];

if(_viewController.minutes&lt;0){

    if(_viewController.fadeSeconds&gt;0){
        float div=_viewController.deviceVolume/[_viewController.volumeData.fadeTime floatValue];
        _viewController.musicPlayer.volume=_viewController.musicPlayer.volume-div;
        _viewController.fadeSeconds-=1;

    }
    else {
        [self stop];
        //self.musicPlayer.volume=0.0f;
        // counter=0;
        NSLog(@"closing the sound");
        [_viewController.musicPlayer pause];
        NSLog(@"fade seconds %i minutes ",_viewController.fadeSeconds);
        if(_viewController.dvol==0){
            _viewController.musicPlayer.volume=deviceVolume;
            _viewController.dvol=1;
        }
        back=0.0f;
    }// end of the else

}
</code></pre>
