1

I have to send a POST request to a server with Alamofire but need to change the "id" in the body parameters every time that the previous api call has been completed.

Here is what I did so far, but Alamofire makes 3 request, based on the number of ids contained in an array, but it always perform the api call with the same "id" without doing it progressively like: (id:0 then id:1 then id:2 and so on):

func getVirtualCards() {
    DispatchQueue.main.async {
        for card in self.cardsListId ?? [] {
            CardsClient.getVirtualCards(cardId: card.id, completion: {  [weak self] result in
                switch result {
                case .success(let response):
                    guard let cardInfo = response.cardContext?.cardInfo else {return}
                    self?.cardsList?.append(cardInfo)

                    guard let cardList = self?.cardsList else {return}
                    self?.cardsViewController?.cardsData = cardList
                case .failure(let error):
                    print(error.localizedDescription)
                }
            })
        }
    }
}

How can I get it work correctly?

Thanks for your help

1
  • 1
    this code loops, but there are many problems with this code, you probably just don't see it. There's a guaranteed crash if UI updates in callback end up not on main thread. Also why did you wrap network request in main thread asynch? It's not going to help the callback... In short I recommend to implement proper MVVP, follow some tutorial that explains how to properly organize such requests and UI update, and your problem will likely disappear on its own Commented Jan 14, 2020 at 0:34

0

Browse other questions tagged or ask your own question.