Search code examples
iosswiftasynchronoushttprequestalamofire

Using response data from last async HTTP Request with Alamofire


I am currently using Alamofire to make async http request to my server to get some data back. However, I am making like 3 requests to the server around the same time and I only want to use the data from the last request that I make. However, I am having this issue where the first 2 request gets completed after the 3rd request. Therefore, it resulted in using the data from the first 2 request.

    HttpService.makeGetRequestWithHeader(AppEndPoint.driverLocation, params: params, completionHandler: {(responseData, error) -> Void in
        if let data = responseData {
            self.cars.removeAll()

            let driverLocationListResponse: DriverLocationListResponse = DriverLocationListResponse.fromDictionary(data)
            var driverCars: [DriverCar] = []
            for driver in driverLocationListResponse.driverLocationList {
                let driverCar: DriverCar = DriverCar(driverId: driver.driverId!, latitude: driver.latitude!, longitude: driver.longitude!)
                driverCars.append(driverCar)
            }

            self.addCars(driverCars)
        }
    })

Does anyone know how to solve this issue? Thanks!


Solution

  • Keep a reference to this request and cancel it before running.