Tuesday 17 April 2012

Running thread when application main thread goes to suspend ( background)

Write this code inside AppDelegate

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

    UIApplication *app = [UIApplication sharedApplication];
    UIBackgroundTaskIdentifier bgTask;
   
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
    }];
}



and start  a secondary thread any where in the app
// this method running infinite
- (void)secondaryThread{
    long i = 0l;
    while (YES) {
        sleep(1);
        NSLog(@"Thread %ld",i++);
        if (i<-1) {
            i = 0;
        }
    }
}

// start thread any where
// this code start thread
[NSThread detachNewThreadSelector:@selector(secondaryThread) toTarget:self withObject:nil];

No comments:

Post a Comment