-1

我有组和队列

let group = DispatchGroup()
let queue = DispatchQueue(label: "downloadImages", attributes: .concurrent)

在我的功能中,我发送 3 个请求

func getImages() {
        networkService.getImages(find: film.originalTitle) { [weak self] result in
            guard let self = self else { return }
            self.queue.async(group: self.group) {
                switch result {
                case let .success(posters):
                    guard let unwrappedPostersResult = posters?.results else { return }
                    self.posters?.append(contentsOf: unwrappedPostersResult)
                case let .failure(error):
                    self.view?.failure(error: error)
                }
            }
        }

        networkService.getImages(find: film.originalLanguage) { [weak self] result in
            guard let self = self else { return }
            self.queue.async(group: self.group) {
                switch result {
                case let .success(posters):
                    guard let unwrappedPostersResult = posters?.results else { return }
                    self.posters?.append(contentsOf: unwrappedPostersResult)
                case let .failure(error):
                    self.view?.failure(error: error)
                }
            }
        }

        networkService.getImages(find: "movies") { [weak self] result in
            guard let self = self else { return }
            self.queue.async(group: self.group) {
                switch result {
                case let .success(posters):
                    guard let unwrappedPostersResult = posters?.results else { return }
                    self.posters?.append(contentsOf: unwrappedPostersResult)
                case let .failure(error):
                    self.view?.failure(error: error)
                }
            }
        }

他们工作得很好,但是当我添加 DispatchGroup group.notify() 时从未调用

   group.notify(queue: .main) { [weak self] in
            guard let self = self else { return }
            self.view?.success()
        }

完成请求后如何调用 group.notify()?

4

1 回答 1

1

创建 DispatchGroup() 时,您需要为所有网络服务添加 group.enter() 和 group.leave()。

let group = DispatchGroup()
let queue = DispatchQueue(label: "downloadImages", attributes: .concurrent)
// Enter group
group.enter() 
networkService.getImages(find: film.originalTitle) { [weak self] result in
            guard let self = self else { return }
            self.queue.async(group: self.group) {
                switch result {
                case let .success(posters):
                    guard let unwrappedPostersResult = posters?.results else { return }
                    self.posters?.append(contentsOf: unwrappedPostersResult)
                  // leave group
                    group.leave()
                case let .failure(error):
                    self.view?.failure(error: error)
                   // leave group
                   group.leave()
                }
            }
        }
于 2021-05-05T18:07:34.427 回答