Gibraltar
Gibraltar

Reputation: 1115

Swift: How to Stop Multiple API Calls

My app allows users to search for a specific thing after which I make multiple API calls from different sources to get information on what they searched.

I want to add a Stop button so that a user can stop the search if, for example, they have a bad wifi connection and the search is taking too long. I have my API calls in different methods, so I won't know which one is running when the user clicks the Stop button.

Is anyone familiar with a way to stop all functions or even just the API calls running in the app when the user clicks Stop?

Upvotes: 0

Views: 2390

Answers (2)

froggomad
froggomad

Reputation: 1915

While using an OperationQueue is arguably a better solution, you could also store multiple URLSessionDataTasks in an array and use .cancel() to stop them all in a loop.

Ex:

let task1 = URLSession.shared.dataTask(...
let task2 = URLSession.shared.dataTask(...

let taskArr = [task1, task2]

for task in taskArr {
    task.cancel()
}

Upvotes: 0

Leo
Leo

Reputation: 24714

You may try this:

  • Create an Operation for every API call
  • Add Operation to OperationQueue to start API call
  • Call operationQueue.cancelAllOperations() to cancel all API call.

Upvotes: 2

Related Questions