【问题标题】:How to call a method every nth minute while app is in background?应用程序在后台时如何每n分钟调用一次方法?
【发布时间】:2013-05-23 09:11:02
【问题描述】:

大家好,我需要在应用程序处于后台时调用一个方法。现在我正在尝试实现这一点,但从未调用过计时器。

- (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,但不会调用计时器。

【问题讨论】:

    标签: ios nstimer


    【解决方案1】:

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

    然后从 Appdeligate 你可以管理这个线程

    你应该检查

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

    希望对你有帮助

    【讨论】:

    • 您好,感谢您的回复,但其背后的目标是每 5 分钟调用一次 StartUpdatingLocation,这样它就不会耗尽电池电量。我使用了 Startmonitoringsignificantchanges 但我需要最大的准确性。
    • 你应该使用位置管理器并设置最佳精度,然后你可以启动你的计时器,每 5 分钟你可以调用一次 startUpdatingLocation,你应该为导航应用设置 UIBackground 模式,然后你的工作会很容易做到的
    • 还有一件事你应该删除代码 UIApplication* app = [UIApplication sharedApplication]; bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }];来自后台方法函数
    • 只有当我的应用程序进入前台时才会调用我的计时器。我所做的是在应用程序进入后台时初始化我的 locationmanger 并在那里初始化 Nstimer 我执行 startUpdatingLocation 并且当我进入应用程序时,即应用程序是然后在前台调用 didupdatelocation。有什么想法吗?
    • 导航应用程序的 UIBackground 模式你的意思是在 plist 文件中添加我已经做过的条目
    猜你喜欢
    • 2012-05-01
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多