perform background task on different thread in iOS -
how preform operation in background on different thread, if executed on main thread blocking ui of app. 1 have idea how it?
even if prints nslog in background fine. want run following thing in no matter if user presses home button. in viewcontroller did :
- (ibaction)btnstartclicked:(uibutton *)sender { [nsthread detachnewthreadselector:@selector(startbgtask) totarget:self withobject:nil]; } -(void)startbgtask{ [[[uiapplication sharedapplication] delegate] performselector:@selector(startthread)]; }
and in appdelegate.m have method
-(void) startthread { @autoreleasepool { (int = 0; < 100; i++) { dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{ nslog(@"current progress %d", i); }); [nsthread sleepfortimeinterval:1]; } } }
it prints integer 1 100 on interval of 1 second.
add these properties .h file
@property (nonatomic, strong) nstimer *updatetimer; @property (nonatomic) uibackgroundtaskidentifier backgroundtask;
now replace btnstartclicked method this,
-(ibaction)btnstartclicked:(uibutton *)sender { self.updatetimer = [nstimer scheduledtimerwithtimeinterval:0.5 target:self selector:@selector(calculatenextnumber) userinfo:nil repeats:yes]; self.backgroundtask = [[uiapplication sharedapplication] beginbackgroundtaskwithexpirationhandler:^{ nslog(@"background handler called. not running background tasks anymore."); [[uiapplication sharedapplication] endbackgroundtask:self.backgroundtask]; self.backgroundtask = uibackgroundtaskinvalid; }]; } -(void)calculatenextnumber{ @autoreleasepool { // executed no matter app in foreground or background } }
and if need stop use method,
- (ibaction)btnstopclicked:(uibutton *)sender { [self.updatetimer invalidate]; self.updatetimer = nil; if (self.backgroundtask != uibackgroundtaskinvalid) { [[uiapplication sharedapplication] endbackgroundtask:self.backgroundtask]; self.backgroundtask = uibackgroundtaskinvalid; } = 0; }
Comments
Post a Comment