如何在应用程序处于后台时每隔n分钟调用一次方法?
大家好,我需要调用一个方法,当应用程序在后台。 这是现在我正试图实现这一点,但计时器从来没有被调用。
- (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]; }
我需要在应用程序处于后台的checkUpdates
每隔一分钟或几秒钟调用方法checkUpdates
。请注意, initTimer
在应用程序进入后台时调用,但定时器从不调用。
如果你想在后台使用应用程序,苹果将不允许在后台使用该应用程序,你必须使用“UIBackgroundModes”。
之后从Appdeligate你可以pipe理这个线程
你应该检查
希望对你有帮助