从完成处理程序中断循环

时间:2019-08-19 03:22:08

标签: swift

我有4种类别:[“ PR”,“ Pickup”,“ Recommend”,“ New”]

对于每种类型,我需要调用服务器来获取文章。 问题是,如果我有足够的20篇文章,我想停止获取。 我不想处理每个回调。有更好的方法吗?

我正在使用DispatchGroup,但无法正常工作。这是我的代码:

let types: [FeedTimeline] = [.special, .pr, .pickup, .lastPost]
for type in types {
    dispatchGroup.enter()
    self.getArticles(of: type, page: currentPage) { [unowned self] (articles) in
        self.articles.append(contentsOf: articles ?? [])
        self.dispatchGroup.leave()
    }
    dispatchGroup.notify(queue: .main) {
        if self.articles.count >= 20 {
            self.currentSubType = type
            //I want to stop request here 
        }
        self.tableView.reloadData()
    }
}

1 个答案:

答案 0 :(得分:1)

您无需在articles count dispatchGroup's中检查notify closure,而是需要在调用getArticles(of:page:handler:)方法之前执行此操作,即< / p>

    types.forEach { (type) in
        if self.articles.count < 20 {
            dispatchGroup.enter()
            self.getArticles(of: type, page: currentPage) {[unowned self] (articles) in
                self.articles.append(contentsOf: articles ?? [])
                dispatchGroup.leave()
            }
        }
    }

接下来,dispatchGroup's notify closure就像

dispatchGroup.notify(queue: .main) {
    DispatchQueue.main.async {
        self.tableView.reloadData()
    }
}