Вопрос

I got stuck in a problem. I'm trying to run a timer in a method which itself is in background resulting my timer is not initiating. I got to know some where that timer can't be initialized in background so is there any way to do this?

Это было полезно?

Решение

You can perform the operation on main thread.

[self performSelectorOnMainThread:@selector(initTimer) withObject:nil waitUntilDone:NO];

and then

- (void)initTimer {
// Init your timer here.
}

Другие советы

You can try Background Fetch in ios7 to run code on background

Try this :

// provide value as required. Time here is 3 sec
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC); 

dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    // do your task
});

As pointed out by @Bryan Chen, you can schedule a method to be run on the current thread using the following code:

dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC);
dispatch_after(when, dispatch_get_current_queue(), ^(void) {
    [self myTimedMethod];
});

You cannot use NSTimer in a background thread unless you are maintaining a run loop on that thread.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top