Reputation: 65
I have an issue that my NSTimer doesn't work when the app is working in backgroud. on the simulator it is work, on the device it is not.
my code on the AppDelegate.m:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"enter background");
notiTimer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(checkNotification) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:notiTimer forMode:NSDefaultRunLoopMode];
}
and the method I am trying to run in loop:
-(void)checkNotification {
NSLog(@"running loop in bg");
userdetails =[NSUserDefaults standardUserDefaults];
userid = [userdetails objectForKey:@"userid"];
username = [userdetails objectForKey:@"username"];
if (userid != NULL && username != NULL) {
notifString = [NSString stringWithFormat:@"userid=%@", userid];
notifData = [NSData dataWithBytes: [notifString UTF8String] length: [notifString length]];
urlreq = [[NSMutableURLRequest alloc] initWithURL:notifUrl];
[urlreq setHTTPMethod: @"POST"];
[urlreq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[urlreq setHTTPBody: notifData];
sendreq = [NSURLConnection sendSynchronousRequest:urlreq returningResponse:nil error:nil];
response =[[NSString alloc] initWithBytes:[sendreq bytes] length:[sendreq length] encoding:NSUTF8StringEncoding];
responsTrimmed = [response stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
splitResponse = [responsTrimmed componentsSeparatedByString: @","];
if ([splitResponse[0] isEqualToString:@"1"]) {
NSLog(@"%@",splitResponse[1]);
}
else {
NSLog(@"err");
}
}
}
now once at the app enter to background I get at the debugger the NSLog:
NSLog(@"enter background");
but the run loop doesn't work and the method doesn't call in loop and I don't get NSLog
NSLog(@"running loop in bg");
on the debugger, any idea ?
Upvotes: 0
Views: 792
Reputation: 3870
When your application goes in background, it is "frozen" by the OS, so no task can be executed in the normal way. The application itself should declare how it handles background task, but you are limited to one of this situation:
So in order to execute some code, you have to start a background task at quit time.
Here is the Apple documentation for Background Execution, hope it can help you.
Upvotes: 5