计时器:如何在后台保持计时器激活

时间:2011-12-23 07:47:19

标签: iphone objective-c xcode cocoa-touch timer

在我的iPhone定时器应用程序中,

计时器应该在后台运行。

所以, 我在appdelegate中设置了通知,它完美地工作了...... 有了这个,我从视图控制器调用方法,使计时器活着。

看一些代码......

App代理

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */

    NSLog(@"Time Remaining %d",(self.viewController.totalSeconds-self.viewController.totalCount));
    [self.viewController selectandnotify:(self.viewController.totalSeconds-self.viewController.totalCount)];
    [self.viewController stopTimer];
    [self.viewController startTimerAction];

}

我在这里调用方法 startTimerAction 方法,这个方法在我的视图控制器中...看看这个......

-(void)startTimerAction
{
 timer_main = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self    selector:@selector(ShowActicity) userInfo:nil repeats:YES];
}

哪个是NSTimer

每次

- ShowActivity 方法会在每秒后调用...以下是我的视图控制器......

-(void)ShowActicity
{

    NSLog(@"Total Counts %d",totalCount);
    if (totalCount == totalSeconds) {
        if ([timer_main isValid]) {
            [timer_main invalidate];
            isTimeOver = YES;
            [self generateLog];
        }
    } else {
        totalCount++;

        seconds =seconds + 1;
        if(seconds > 59)
        {
            minutes = minutes + 1;
            seconds= 0;
        }

}

如何从视图控制器每次调用此方法.....

  • 如何从appdelegate每次调用showActivity方法...

    • 我应该使用委托吗

    • 我应该在Appdelegate中创建showActivity和计时器..

  • 实际上我希望这个应用程序在应用程序中切换视图时运行.....

我认为如果我委托代表是一个不错的选择?

任何其他方式....请提出一些建议

1 个答案:

答案 0 :(得分:4)

一般使用此代码进行后台运行。后台计时器不起作用

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UIApplication*    app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task.
        [self startTimerAction];
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW3