iphone后台进程在我的应用程序中长期不起作用



我正在我的应用程序中使用iphone后台进程。它在后台运行,但10分钟后它将终止我的应用程序。而且长时间不工作。

我的应用程序包含一个带有timmer的计数器。当视图加载时,我的计数器将启动,当我单击主页按钮时,它将在后台运行。在后台,它运行得很完美,但10分钟后,它停止了我的后台进程。以下是我的代码。

在.h文件中。

IBOutlet UILabel *thecount;
int count;
NSTimer *theTimer;
UIBackgroundTaskIdentifier counterTask;

在我的.m 中

- (void)viewDidLoad {
    UIBackgroundTaskIdentifier bgTask = nil;
    UIApplication  *app = [UIApplication sharedApplication];

    counterTask = [[UIApplication sharedApplication]
                   beginBackgroundTaskWithExpirationHandler:^{
                       [app endBackgroundTask:counterTask]; 
                       //counterTask = UIBackgroundTaskInvalid;
                       // If you're worried about exceeding 10 minutes, handle it here
                       theTimer=[NSTimer scheduledTimerWithTimeInterval:0.5
                                                                 target:self
                                                               selector:@selector(countUp)
                                                               userInfo:nil
                                                                repeats:YES];
                   }];
    count=0;
    theTimer=[NSTimer scheduledTimerWithTimeInterval:0.5
                         target:self
                         selector:@selector(countUp)
                         userInfo:nil
                         repeats:YES];
    [super viewDidLoad];
}
  • (void)countUp{

     count++;
     NSString *currentCount;
     currentCount=[[NSString alloc] initWithFormat:@"%d",count];
     NSLog(@"timer running in background :%@",currentCount);
     thecount.text=currentCount;
     [currentCount release];
    

}

上面的代码只是用来计数前台和后台的数字。但10分钟后就不起作用了。

因此,请帮助我,并为我提供一些帮助。

10分钟是长时间运行的后台任务的最大时间。iOS并不提倡长时间运行后台进程的想法,为了用户的利益,你不应该尝试这样做。

为了让您的代码运行更长时间,一些其他外部事件可能会使您的应用程序再次被唤醒或保持运行,例如GPS定位事件、在VoIP类型的应用程序中播放音频或传入VoIP连接。

最新更新