iOS:仅当应用程序处于活动状态时重复任务(无背景)

mm2*_*m24 0 iphone objective-c nsoperationqueue grand-central-dispatch ios

我发现有几篇帖子询问如何运行后台任务。这可以。我得到它。Apple有一个指南,仅适用于某些类型的应用程序。

我的用例如下:我只想在聊天应用程序位于前台时更新该应用程序的联系人列表。因此,当应用程序分别处于以下状态时,我可以启动/暂停/恢复:didBegan、didEnterBackground、didResumeFromBackground。

我如何使用 GCD 来实现这一目标?

换句话说,我如何以重复的方式安排异步任务并且仅每隔一段时间(例如每 0.5 秒)调用一次?有没有使用 NSOperationQueue 的好的实现?

编辑2:我想要执行的任务:

1:从 Web 服务 API 获取包含联系人信息的 JSON 数据对象(在线状态、设备、上次查看时间)

2:从 Web 服务 API 获取包含给用户的消息的 JSON 数据对象

编辑: NSOperation 文档将操作定义为只能用作“单次”的操作,因此创建递归操作可能不是解决此问题的最佳方法。

Leo*_*ica 5

下面是一些关于如何使用计时器以及 GCD 和操作队列来实现此目的的代码。

NSOperationQueue* queue = [NSOperationQueue new];
[queue setMaxConcurrentOperationCount:1]; //Make serial.
//dispatch_queue_t queue = dispatch_queue_create("queue", NULL); //Serial queue.
Run Code Online (Sandbox Code Playgroud)

先生们,开始计时吧:

[NSTimer scheduledTimerWithTimeInterval:0.0 target:appDelegate selector:@selector(timerTicked:) userInfo:nil repeats:NO]; //Start a timer with 0 so it ticks immediately.
Run Code Online (Sandbox Code Playgroud)

现在在方法中:

- (void)timerTicked:(NSTimer*)timer
{
    NSLog(@"Timer ticked!");
    void (^block)() = ^{
        //Do what you need here.

        //Start a new timer.
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:appDelegate selector:@selector(timerTicked:) userInfo:nil repeats:NO];
    };

    [queue addOperationWithBlock:block];
    //dispatch_async(queue, block);
}
Run Code Online (Sandbox Code Playgroud)

我使用应用程序委托是因为计时器保留目标对象,所以我不想将其放在视图控制器中。您可以在计时器滴答后立即安排下一个计时器,也可以在操作/任务完成后安排下一个计时器,这是我更喜欢做的。