Oleg Gordiichuk Oleg Gordiichuk - 3 months ago 13
iOS Question

How do I optimize chaining async requests in Swift

I have code that do requests chaining like A->B->C and I am using

URLSession
all requests are done in right order and with expected behavior. But i am wondering how I can optimize this chaining because it looks quite complex and not reusable. I am looking for the suggestion how I can do this chaining in more flexible way.

My code:

URLSession.shared.dataTask(with: URLRequest(url: URL(string: "first")!)){ data , res , err in
let second = URLRequest(url: URL(string: "second")!)
URLSession.shared.dataTask(with: second){ data , res , err in
let third = URLRequest(url: URL(string: "second")!)
URLSession.shared.dataTask(with:third){ data , res , err in
}.resume()
}.resume()
}.resume()

Answer

As @Paulw11 suggested:

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
}