Wednesday, 14 May 2014

Run timer in background thread

ViewController.H


@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;

ViewController.M

self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        NSLog(@"Background handler called. Not running background taxsks anymore.");
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countup)userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    });

-(void)countup { 
  //Here i done another action run in main thread
 dispatch_async(dispatch_get_main_queue(), ^{  
               ViewController *Vc=[self.storyboard instantiateViewControllerWithIdentifier:@"view"];
                [self.navigationController pushViewController:Vc animated:YES];
            });
}

No comments:

Post a Comment