As @ Paulw11 said:
PromiseKit + PMKFoundation
import PromiseKit import PMKFoundation let session = URLSession.shared firstly { session.dataTask(with: URLRequest(url: URL(string: "first")!)) } .then { data in session.dataTask(with: URLRequest(url: URL(string: "second")!)) } .then { data in session.dataTask(with: URLRequest(url: URL(string: "third")!)) } .then { data -> () in // The data here is the data fro the third URL } .catch { error in // Any error in any step can be handled here }
With a repeat of 1 (and only 1) you can use recover . recover is similar to catch , except it is expected that the previous then can be repeated. However, this is not a loop and is executed only once.
func retry(url: URL, on error: Error) -> Promise<Data> { guard error == MyError.retryError else { throw error } // Retry the task if a retry-able error occurred. return session.dataTask(with: URLRequest(url: url)) } let url1 = URL(string: "first")! let url2 = URL(string: "second")! let url3 = URL(string: "third")! let session = URLSession.shared firstly { session.dataTask(with: URLRequest(url: url1)) } .then { data in session.dataTask(with: URLRequest(url: url2)) } .recover { error in retry(url: url2, on: error) } .then { data in session.dataTask(with: URLRequest(url: url3)) } .recover { error in retry(url: url3, on: error) } .then { data -> () in // The data here is the data fro the third URL } .catch { error in // Any error in any step can be handled here }
NOTE. To make this work without specifying return types and the need for a return , I need then and recover be exactly 1 line. Therefore, I create methods for processing.
source share