gpt4 book ai didi

iOS:仅当 APP 处于事件状态时重复任务(无后台)

转载 作者:行者123 更新时间:2023-11-28 19:04:09 25 4
gpt4 key购买 nike

我找到了几个 post询问如何运行后台任务。这可以。我得到它。有一个guideline来自 Apple,并且只能针对某些类型的应用程序完成。

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

如何使用 GCD 实现此目的?

换句话说,我怎样才能以重复的方式安排一个异步任务,并且只每隔一段时间(比如每 0.5 秒)调用一次?使用 NSOperationQueue 有好的实现吗?

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

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

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

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

最佳答案

下面是一些代码,说明如何使用计时器以及 GCD 和操作队列来实现这一点。

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

先生们,开始计时吧:

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

现在在方法中:

- (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);
}

我使用应用程序委托(delegate)是因为计时器保留了目标对象,所以我不想将它放在 View Controller 中。您可以在计时器滴答后或操作/任务完成后立即安排下一个计时器,这是我喜欢做的。

关于iOS:仅当 APP 处于事件状态时重复任务(无后台),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22001341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com