Search code examples
iosxcodeswiftgrand-central-dispatchalamofire

Using Alamofire with a loop to send multiple requests based on Tableview count


I am trying to send multiple requests based on the tableview count using a for loop. I know Alamofire is asynchronous. The problem I have is when I use a loop to call the function, the x value becomes out of sync with the response since it is asynchronous. What is the best approach to essentially guard the int value passed into the POST request until the completion handler returns a value. Would a synchronous approach be best or is there a way to asynchronously pass multiple values? If so, how would I implement?

    for var x = 0; x < tableArray.param.count; ++x { // how to lock x value until Tasks completes

    Alamofire.request(.POST, "https://mygateway/rest/dosomething/\(x)", parameters : parameters, encoding: .JSON)
    .responseJSON {
        (request, response, json) in

        if json.value != nil {

            let statuses = JSON(json.value!)

            for (key, value): (String, JSON) in statuses {

                if key == "revision" {

                    let rev = value

                    self.tableArray.param[x].revision = rev.stringValue
                    // this determines the table cell setup
                }
            }
        }
    }
}
self.tableView.reloadData()

Solution

  • Since x has been declared as var. Closure will capture x as mutable version. Therefore, x will increase overtime when the loop pass.

    You can capture x with let. Since let is immutable . It will never be changed. Use that value inside the closure. For example

    for var x = 0; x < tableArray.param.count; ++x {  
        let capturedX = x
        // do something with capturedX
        self.tableArray.param[capturedX].revision = rev.stringValue
    }
    

    or just use range loop. It's more elegant and clean.

    for x in 0..< tableArray.param.count{
        // do the same way you do with x
        // ...
    }