liux liux - 23 days ago 15
iOS Question

How to run a Alamofire request inside another Alamofire request?

I want to POST to a website first and then GET another website for the data.

And change the key in the POST, and keep doing this in a for-loop for 5 times to get different data.

However, the program always first run the POST for 5 times and secondly run the GET for another 5 times, which makes me get the same data.

Here is the code:

for i in 1...5{

let postData: Parameters = ["key": "\(i)"]

Alamofire.request(" POST Website", method: HTTPMethod.post, parameters: postData, encoding: URLEncoding.default, headers: self.headers).response(completionHandler: { (ressponse) in

Alamofire.request(" GET Website ", method: HTTPMethod.get, headers: self.headers).response(completionHandler: { (response) in

// Get Data
})
})
}


How can I fix this?

Thanks

Answer

You should understand the difference between synchronous and asynchronous operations. There are lots of answers on the topic here on SO or anywhere else. Example

Basically your for loop executes almost immediately, it doesn't wait for any response either from POST or GET requests. Each time inside the loop you schedule POST request and every time it is finished, another GET request is being sent. So you're getting this behavior:

POST, POST, POST, POST, POST .......... GET, GET, GET, GET, GET

If you want it to be this:

POST .... GET ..... POST ...... GET ...... and so on ....

you should call POST request inside the success block of GET request, like this:

func postRequest(index: Int, count: Int) {
    if count > 0 {
        let postData: Parameters = ["key": "\(index)"]
        Alamofire.request(" POST Website", method: HTTPMethod.post, parameters: postData, encoding: URLEncoding.default, headers: self.headers).response(completionHandler: { (response) in
            Alamofire.request(" GET Website ", method: HTTPMethod.get, headers: self.headers).response(completionHandler: { (response) in
                // Get Data
                postRequest(index+1, count-1)
            })
        })
    }
}
Comments