繁体   English   中英

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

[英]Timer: how to remain timer active in Background

在我的iPhone Timer应用程序中,

其中计时器应该在后台运行。

所以,我已经在appdelegate中设置了通知,它完美地工作......我正在调用视图控制器中的方法,这使得计时器处于活动状态。

看看一些代码......

应用代表

- (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和计时器吗?

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

我想如果我让委托是个不错的选择?

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

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

- (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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM