Search code examples
swiftalamofire

Run Alamofire request after finishing another Alamofire request


I would like to run an Alamofire request that is using the result of a previous Alamofire request as a parameter. To make it simple:

    //Code1
    Alamofire.request("URL", method: HTTPMethod.post, parameters: ["id": id as NSString)], encoding: URLEncoding.httpBody).response(completionHandler: { (response) in
        let json = response.data
        do {
            print("This should be First")
            let data = try JSON(data: json!)
            let alllastmessages = data["Messages"].arrayValue
            for  i in 0..<alllastmessages.count {
                self.List.append(alllastmessages[i]["message"].stringValue)
            }}
        catch _{}
    })
    //End Code1

    //Code2
    print("This should be Last")
    for  i in 0..<List.count {
        Alamofire.request("URL2", method: .post , parameters: ["id": id as NSString] , encoding: URLEncoding.httpBody).response(completionHandler: { (response) in
            //Do Something
        })
        self.tableView.reloadData()
    }
    //End Code2

(This code is simplified, I'm just looking for a way to make Code1 run before Code2)


Solution

  • Easiest way IMO is to use DispatchGroup, you can read more about it here: https://developer.apple.com/documentation/dispatch/dispatchgroup

    Here's some code that works fine for me:

        DispatchQueue.global(qos: .userInitiated).async {
            let group = DispatchGroup()
            group.enter()
    
            print("\(Date()) Start request 1!")
            Alamofire.request("https://github.com/CosmicMind/Material",
                              method: .get ,
                              parameters: [:] , encoding: URLEncoding.httpBody).response(completionHandler: { (response) in
                                print("\(Date()) Request 1 completed!")
                                group.leave()
                              })
    
            group.wait()
    
            print("\(Date()) Start request 2!")
            Alamofire.request("https://github.com/CosmicMind/Material",
                              method: .get ,
                              parameters: [:] , encoding: URLEncoding.httpBody).response(completionHandler: { (response) in
                                print("\(Date()) Request 2 completed!")
                              })
        }
    

    Prints:

    2017-12-22 18:24:45 +0000 Start request 1!
    2017-12-22 18:24:47 +0000 Request 1 completed!
    2017-12-22 18:24:47 +0000 Start request 2!
    2017-12-22 18:24:49 +0000 Request 2 completed!