提问者:小点点

我如何在从两个异步函数接收数据后执行一个动作?迅捷


我执行2个http请求,并从它们异步获取数据。数据收到后,我需要在其基础上形成一个数组并重新加载表,我如何做到这一点呢?代码:

override func viewDidLoad() {
        super.viewDidLoad()
        
        ApiManager.shared.getStocks(completion: {result in
            DispatchQueue.main.async {
                switch result {
                case .success(let stocks):
                    self.stocks = stocks
                case .failure:
                    self.stocks = []
                }
            print(self.stocks.count)
            }
        })
        ApiManager.shared.getDowJones (completion: { result in
            DispatchQueue.main.async {
                switch result {
                case .success(let dowJones):
                    self.dowJones = dowJones
                case .failure:
                    self.dowJones = []
                }
                print(self.dowJones.prefix(10))
            }
        })
    }

共2个答案

匿名用户

最佳匹配DispatchGroup

   let g = DispatchGroup()
   g.enter()
    ApiManager.shared.getStocks(completion: {result in
        DispatchQueue.main.async {
            switch result {
            case .success(let stocks):
                self.stocks = stocks
            case .failure:
                self.stocks = []
            }
        g.leave()
        print(self.stocks.count)
        }
    })
   g.enter()
    ApiManager.shared.getDowJones (completion: { result in
        DispatchQueue.main.async {
            switch result {
            case .success(let dowJones):
                self.dowJones = dowJones
            case .failure:
                self.dowJones = []
            }
            g.leave()
            print(self.dowJones.prefix(10))
        }
    })

    g.notify(queue:.main) {
        // reload here
     }

匿名用户

您可以将一个动态变量作为APISuccess,然后在API成功时激发它,现在您所需要做的就是将该变量绑定到视图控制器中,并编写一个代码以保护它的bolck。

相关问题