【问题标题】:NSTimer should run continuously in the background in iOS 7NSTimer 应该在 iOS 7 的后台连续运行
【发布时间】:2014-05-21 00:51:29
【问题描述】:

我有 NSTimer,它根据我当前的时间调用 startUpdatingLocation 或 StopUpdatingLocation 的方法。如果我当前的时间少于晚上 8 点,它将停止更新位置,但我的计时器将在后台连续运行。我既没有删除我的应用程序,也没有在后台删除我的应用程序。

我需要在后台连续运行计时器,并且应该在当前时间是第二天早上 8 点时开始更新位置。现在我的应用程序正在后台运行,但我的位置不会在第二天早上 8 点开始更新。我在 iOS 7 中进行了测试。只有在我从后台启动应用程序后,它才会开始更新位置。

谁能建议我如何在 iOS 7 的后台连续运行计时器?

 - (void)applicationDidEnterBackground:(UIApplication *)application
      {
            UIDevice *device = [UIDevice currentDevice];
            BOOL backgroundSupported = NO;
            if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {
                backgroundSupported = YES;
            }

            if (backgroundSupported) 
            {
                bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ [[UIApplication sharedApplication] endBackgroundTask:bgTask];
                }];


               NSTimer *preventSleepTimer = [[NSTimer alloc] initWithFireDate:[NSDate          dateWithTimeIntervalSinceNow:0] interval:20.0f target:self selector:@selector(switchingOnLocation) userInfo:nil repeats:YES];
            self.mTimer = preventSleepTimer;
            [preventSleepTimer release];

            // Add the timer to the current run loop.
            [[NSRunLoop currentRunLoop] addTimer:self.mTimer forMode:NSRunLoopCommonModes];
        }
    }

【问题讨论】:

    标签: ios7 nstimer core-location


    【解决方案1】:
       NSTimer *currentCycleTimer;
    
    UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
    UIApplication *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
    }];
    [currentCycleTimer invalidate];
    currentCycleTimer=nil;
    secondsLeft = 120;
    currentCycleTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(Countdown) userInfo:nil repeats: YES];
    
    -(void) Countdown
    {
      [currentCycleTimer invalidate];
       currentCycleTimer=nil;
    }
    

    【讨论】:

      【解决方案2】:

      无法在后台随心所欲。您必须遵守 Apple 的协议。不幸的是,Apple 不允许您在后台运行 NSTimers(曾经在 iOS 6 中存在漏洞,但他们已修复),而是为您提供了一组指令来获取位置更新。

      阅读 Apple 的 this article,它彻底解释了如何在后台运行应用程序。

      为了您的利益,我建议在您的服务器上实施APN 服务,并在需要时推送到手机 - 在您的情况下是早上 8 点。它有它的缺点,但这是我现在能想到的唯一方法。

      【讨论】:

      • 什么会起作用? APN?我看不出为什么不这样做,但正如你所说 - 你会耗尽电池......但这只是任何基于位置的应用程序的命运:-)
      • 是的,我计划安排本地通知或远程通知。谢谢
      • 如果您对答案感到满意,请将其标记为已接受,这样它就不会在 SO 上的其他问题列表中显示为未回答。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2014-05-02
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 2012-03-02
      相关资源
      最近更新 更多