I have a requirement to create a background processor that only works when the application is in active mode. I tried to make the skeleton of what I am trying to achieve, but could not get it to work.
I want this background processor to stop sleeping when the application goes to the inactive stage and resume when the application goes into active mode. I provided the skeleton of what I did below. Can someone help me fix this.
Appdelegate.h
AppDelegate.m
#import "AppDelegate_iPhone.h" #import "BackgroundProcessor.h" @implementation AppDelegate_iPhone @synthesize processor; -(BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { processor = [[BackgroundProcessor alloc]init]; [processor Start]; return YES; } -(void) applicationDidEnterBackground:(UIApplication *)application { [processor Sleep]; NSLog(@"Entered Background"); } -(void) applicationDidBecomeActive:(UIApplication *)application { [processor Resume]; NSLog(@"Became Active"); } @end
BackgroundProcessor.h
BackgroundProcessor.m
#import "BackgroundProcessor.h" @implementation BackgroundProcessor @synthesize processor; -(id) init { self = [super init]; if(self) { processor = [[NSThread alloc] initWithTarget:self selector:@selector(workloop) object:nil]; } return self; } -(void) Start { if(processor) [processor start]; } -(void) Sleep { // [processor [NSThread sleepForTimeInterval: 0.1]; } -(void) workloop { NSLog(@"Background Processor Processing ...."); [NSThread sleepForTimeInterval:0.1]; } - (void) Resume { NSLog(@"Background Resuming ...."); [NSThread sleepForTimeInterval: 0.1]; }
I can't get a workloop to make it work all the time. Appreciate if someone can help me decide why the background
Tried it on the advice of Joshua Smith
#import "BackgroundProcessor.h" @implementation BackgroundProcessor -(id) init { self = [super init]; if(self) { queue = [[NSOperationQueue alloc] init]; NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(workloop) object:nil]; [queue addOperation:operation]; } return self; } -(void) workloop { NSLog(@"Sleeping for 10 seconds"); sleep(10); NSLog(@"Background Processor Processing ...."); NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(workloop) object:nil]; [queue addOperation:operation]; } @end
source share