在序列Swift中运行两个Alamofire请求

时间:2017-07-16 21:20:46

标签: swift asynchronous alamofire grand-central-dispatch

我正在使用找到here的异步库,以便在从ViewDidLoad运行第二个之前等待第一个alamofire请求完成。该库似乎很简单,但我永远无法获得第一个等待请求。我的代码如下:

let group = AsyncGroup()

         group.utility
        {
            self.getToken()
        }

        group.wait()

        self.getDevices()

我希望getToken函数在继续执行getDevices请求之前完成Alamofire请求及其完成处理程序。两者都是非常简单的Alamofire请求。

修改

这是getToken请求。在调用第二个alamofire请求之前,token变量未通过alamofire响应进行更新。

func getToken()

    {
        let httpheader: HTTPHeaders =

            [
                "Content-Type": "application/json"
        ]



        // Dev

        let param = [params here]


        Alamofire.request("url", method: .post, parameters: param, encoding: JSONEncoding.default, headers:httpheader).validate()
            .responseData { response in
                switch response.result {

                case .success:
                    if let data = response.data {

                        let xml = SWXMLHash.parse(data)

                        token = (xml["authResponse"] ["authToken"].element?.text)!

                    }

                case .failure:

                  print ("error")


                }


        }


    }

1 个答案:

答案 0 :(得分:1)

您的getToken看起来更像:

func getToken(whenDone:(String?)->()) {
    let httpheader: HTTPHeaders = [
            "Content-Type": "application/json"
    ]

    // Dev
    let param = [params here]

    Alamofire.request("url", method: .post, parameters: param, encoding: JSONEncoding.default, headers:httpheader).validate()
        .responseData { response in
            switch response.result {

            case .success:
                if let data = response.data {
                    let xml = SWXMLHash.parse(data)
                    token = (xml["authResponse"] ["authToken"].element?.text)!
                    whenDone(token)
                }

            case .failure:
                print ("error")
                whenDone(nil)
            }
    }
}

并且调用序列变为:

getToken() { token ->
    guard let token = token else {
        return
    }

    getDevices()
}