0
我有一个问题,我的NSTimer不起作用,当应用程序在背景中工作。 在模拟器上它是工作的,在设备上它不是。NSTimer不能在后台工作
我对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];
}
,我试图在循环运行的方法:
-(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");
}
}
}
现在一次在应用程序进入到后台我在调试程序获得NSLog:
NSLog(@"enter background");
但运行循环不起作用,该方法不会循环调用,我没有得到NSLo g
NSLog(@"running loop in bg");
关于调试器,有什么想法吗?
是的,当然不是,当应用程序进入后台时它被挂起,包括所有'NSTimer'。有些服务可以在应用程序变为非活动状态后运行 - 但是“NSTimer”不在列表中。 – holex 2014-10-07 16:15:03