2014-10-07 62 views
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"); 

关于调试器,有什么想法吗?

+1

是的,当然不是,当应用程序进入后台时它被挂起,包括所有'NSTimer'。有些服务可以在应用程序变为非活动状态后运行 - 但是“NSTimer”不在列表中。 – holex 2014-10-07 16:15:03

回答

4

当你的应用程序在后台运行时,它被操作系统“冻结”,所以不能以正常方式执行任务。 应用程序本身应该宣布它如何处理后台任务,但是仅限于这种情况的一个:

  • 你需要的时间(通常小于10分钟),少量的:你可以简单地问它
  • 您的应用程序下载东西:你可以让系统继续下载你
  • 稍定任务可以在后台执行,但你必须在你的项目中指定它

所以在为了执行一些代码,你必须ot a 退出时的后台任务

Here is the Apple documentation为后台执行,希望它可以帮助你。