与alamofire Swift 3同步调用

时间:2018-11-06 07:13:17

标签: swift alamofire

我有一个包含字符串列表的数组,我应该调用API进行翻译。在我目前的情况下,for循环完成后,API的响应就来了,我需要一个一个地调用API。我的意思是我需要等待响应发送其他字符串。 这是我的代码

var stringList = ["cat","dog","cup","glass","land"]

for k in 0..< stringList.count {
     self.SetTranslateLetters(WORD: stringList[k], LANG: "AR", completionHandler: { (true) in

    })
}

func SetTranslateLetters(WORD: String, LANG:String, completionHandler:@escaping (Bool) -> ()){

    let param: [String:AnyObject] = [
        "word": WORD as AnyObject,
        "language":LANG as AnyObject
    ]
    let queue = DispatchQueue(label: "com.cnoon.manager-response-queue",
                              qos: .userInitiated,
                              attributes:.concurrent)
    Alamofire.request(url, method: .post,
        parameters: param,
        encoding: JSONEncoding.default,
        headers: ["Content-Type":"application/json; charset=UTF-8"]).responseJSON(queue: queue, options: .allowFragments,
                 completionHandler: { (response:DataResponse<Any>) in

                    switch(response.result) {
                    case .success(let value):
                        print("done")
                        let json_ = JSON(value)
                        // print(json_)


                        let getCoun = json_["TranslateResult"]
                        // print(getCoun)


                        break
                    case .failure(_):
                        print(response.result.error!)
                        if response.result.error?._code == NSURLErrorTimedOut{
                            //TODO: Show Alert view on netwok connection.
                            completionHandler(true)

                        }
                        break
                    }
    })

}

0 个答案:

没有答案