vendredi 27 février 2015

iOS app runs for only 1 second in background

I have 2 classes, ViewController class, and Worker. All the code that I need to run in the background is in the Worker class.


My ViewController looks something like this:



- (void)viewDidLoad {
//create an instance of 'Worker'
}
- buttonClick {
//call the 'manager' method in the worker instance that was just created (do this method as a background thread)
}


My Worker class looks something like this:



- (void)manager {
//call 'repeat' method as a background thread
}

- (void)repeat {
//call 'innerWorker' method as a background thread
}
- (void)innerWorker {
//do work
}


The repeat method needs to get run every second.


I've tried the 2 following ways to make the repeat method run every second.


Method 1 :



timerObj = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(repeatMethod) userInfo:nil repeats:YES];


Method 2: Putting this code at the end of repeat:



dispatch_queue_t q_background = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
double delayInSeconds = 1.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, q_background, ^(void){
[self repeatMethod];
});


Both of these 2 methods work fine as long as the app is in the foreground but the moment I press the home button, the repeat method runs one last time, but does not call the innerWorker method and then the app is suspended. I know this by using NSLogs all over the place.


I realize Method 2 is a bit of a hack but that's fine as this is an internal app that I wont be publishing.


All the methods are called as background threads using this code: eg:



dispatch_queue_t q_background = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_async(q_background, ^{
[self repeatMethod];
});


I'm new to iOS so maybe I'm missing something small here. I just want my app to keep running in the background. Please help me.




Aucun commentaire:

Enregistrer un commentaire