0

I have a list of id's

173577 173581 173565 173578 173564 173571 73576 173580

I want to loop a request with each id in the correct order, but right now it comes back in random order and doesn't get through all the ids.

i also get and error at let stock = imageArray[indexPath.row] saying indexpath out of range and i think its because it doesn't get through all the ids

        let products = newArray[indexPath.row]

        let id = products.id
        print(id)

        let url = URL(string: "https://www.supremenewyork.com/shop/\(id).json")!
        let request = URLRequest(url: url)
        let session = URLSession.shared
        let task = session.dataTask(with: request) { (data, response, error) in

            if let error = error {
                print("ERROR:", error)

            } else if let data = data {
                do {
                    let response = try JSONDecoder().decode(Images.self, from: data)
                    self.imageArray = response.styles
                    print(self.imageArray)
                    } catch {
                        print(error)
                    }
                } else {
                    print("UNEXPECTED ERROR")
            }
        }
        task.resume()

        let stock = imageArray[indexPath.row]
        let x = stock.biggerZoomedURL
        print(x)

The code is working (except let stock = imageArray[indexPath.row] error), i just was seeing if there's a way to loop each id in and print them out in order

GILL
  • 67
  • 6
  • `let stock = imageArray[indexPath.row]` should be under the `print(self.imageArray)` inside the completion closure. What are you trying to do here? – Tj3n Sep 16 '20 at 09:48
  • 1
    Does this answer your question? [Swift 4 async call with for loop execute in order using DispatchGroup, DispatchQueue and DispatchSemaphore](https://stackoverflow.com/questions/46863325/swift-4-async-call-with-for-loop-execute-in-order-using-dispatchgroup-dispatchq) – Joakim Danielson Sep 16 '20 at 09:48
  • i cant put it in there @Tj3n i need to be able to use 'stock' variable – GILL Sep 16 '20 at 09:56
  • and @JoakimDanielson kinda but how would i do it with my request – GILL Sep 16 '20 at 09:57
  • Put most of your code above in a function that takes id and a closure as arguments – Joakim Danielson Sep 16 '20 at 10:17

1 Answers1

0

let stock = imageArray[indexPath.row] seems like you are doing something in cellForRow: method. Well, about this index path out of range you can tackle using this code, it makes a safe index.

public extension Array {
   public subscript (safe index: Int) -> Element? {
      return self.indices ~= index ? self[index] : nil
   }
}

Usage:

let stock = imageArray[safe: indexPath.row]

OR

If you are hitting URL by simply iterating the array then you can use DispathGroup.

burnsi
  • 6,194
  • 13
  • 17
  • 27