1

I am trying to do an API call to return certain data from a web service. I am doing the call in a for loop on every id

The code is:

for data in bookMarkArray  {
  //get the bookMarkID
  let bookMarkId: String = (data as AnyObject).value(forKey: "id") as! String

  let APIURL = "XXXXXXXXXXXXXX/ArticleById?id=" + bookMarkId
  let apiCall = APIManager.shared.fetchArticlesFromApi(API:APIURL)
  let _ = apiCall.done {
      articles -> Void in
      self.certainArticle = articles
      self.articlesDataSource.append(self.certainArticle[0])

      //reload tableview after all bookmarks are fetched
      if index + 1 == bookMarkArray.count  {
          self.tableView.reloadData()
      }
      else{
          index = index + 1
      }

      }.catch {
          error -> Void in
}

The bookmark ids are always in the same order, 1 - 2 - 3. However, every time i open the controller to look at the table view, the articles returned are in different order. Any idea why is this happening?

Example:

First call returns articles in order: 1 - 2 - 3

Second call returns articles in order: 2 - 1 -3

etc.

According to other answers i found, I tried adding serialQueue as the following:

    let serialQueue = DispatchQueue(label: "queuename")
    for data in bookMarkArray  {
        //get the bookMarkID
        let bookMarkId: String = (data as AnyObject).value(forKey: "id") as! String

        let APIURL = "XXXXXXXXXXXXXX/ArticleById?id=" + bookMarkId
        serialQueue.sync {
            let apiCall = APIManager.shared.fetchArticlesFromApi(API:APIURL)
            let _ = apiCall.done {
                articles -> Void in
                self.certainArticle = articles
                self.articlesDataSource.append(self.certainArticle[0])

                //reload tableview after all bookmarks are fetched
                if index + 1 == bookMarkArray.count  {
                    self.tableView.reloadData()
                }
                else{
                    index = index + 1
                }

                }.catch {
                    error -> Void in
            }
      }

But unfortunately it didn't workout for me. Any suggestions or solutions?

Sinan Noureddine
  • 495
  • 5
  • 16

0 Answers0