如何在应用程序处于后台时每隔n分钟调用一个方法?

时间:2013-05-23 09:11:02

标签: ios nstimer

大家好,我需要在应用程序处于后台时调用方法。现在我正在努力实现这一目标,但永远不会调用计时器。

- (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.timer = nil;
        [self initTimer];

    });
}

- (void)initTimer {

    DebugLog(@"timer INIT!!!!!");

    if (self.timer == nil) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.3
                                                      target:self
                                                    selector:@selector(checkUpdates:)
                                                    userInfo:nil
                                                     repeats:YES];
    }
}

- (void)checkUpdates:(NSTimer *)timer{
    [UIApplication sharedApplication].applicationIconBadgeNumber++;

    DebugLog(@"timer FIRED!!!!!");
    [self initTimer];
}

我需要在应用程序处于后台时每N分钟或秒钟调用方法checkUpdates。请注意,当应用程序进入后台时调用initTimer,但永远不会调用计时器。

1 个答案:

答案 0 :(得分:-1)

如果您想在后台使用该应用程序,Apple将不允许在后台使用该应用程序,您必须使用'UIBackgroundModes'。

然后从Appdeligate中你可以管理这个帖子

你应该检查

http://developer.apple.com/library/ios/#documentation/General/Reference/InfoPlistKeyReference/Articles/iPhoneOSKeys.html

希望这会对你有所帮助

相关问题