简体   繁体   中英

How do I perform an action after receiving data from two asynchronous functions? Swift

I execute 2 http requests and get data from them asynchronously. After the data is received, I need to form an array based on it and reload the table, how do I do this? Code:

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

Best fit 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
     }

You can take one dynamic variable as APISuccess and then fire that when you get API success, now all you need to do is bind that variable in your view controller and write a code indise it's bolck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM