0

I am unsure how to resubmit a URLRequest when it's unsuccessful.

I have a function that calls several API's. On one of the API requests, about half the time it is unsuccessful in the first attempt and I have to push the button on my app again to have it run the function again until it goes through. I've traced my code to the exact spot where it is getting caught up, but am unsure how I can handle it to keep trying the request until successful. Below is my code.

        let request = URLRequest(url: URL(string: urlNew)!)

        let session = URLSession.shared

        let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
            // other logic happens here
        })

Most of the time it passes through just fine and everything works as expected. How do I make it keep trying the request however in the case it's not successful? It makes it up to "let task ..." just fine, but that's where it gets caught up. For reference:

urlNew = "MyAPI String value is here"
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jet.B.Pope
  • 642
  • 1
  • 5
  • 25

1 Answers1

0

You can call the function recursively when the request is unsuccessful

func callAPI(urlNew:String) {
    let request = URLRequest(url: URL(string: urlNew)!)

    let session = URLSession.shared

    let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
        // other logic happens here
        guard let data = data, error == nil else {
            self.callAPI(urlNew:urlNew)
            return
        }
    })
    task.resume()
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70