Run Alamofire request after finishing another Alamofire request

两盒软妹~` 提交于 2019-12-31 07:21:52

问题


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)


回答1:


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!



回答2:


The easiest way is just to nest your calls. You can call the 2nd call inside the callback for the first, like so:

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)
        }
        //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
    } catch _{}
})


来源:https://stackoverflow.com/questions/47945332/run-alamofire-request-after-finishing-another-alamofire-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!