Search code examples
iosswiftgoogle-translate

Translate more than one string in iOS with Google Translate API


I am trying to translate some strings with Google Translate API, but I can't translate more than one string at time with the latest vesrsion of API. I am using Alamofire to make request but when I try create parameter dictionary with the same key as in docs, it fails of course. The parameters should be in this format.

{ 'q': 'Hello world', 'q': 'My name is Jeff', 'target': 'de' }

Anybody has some ideas on how to send this request with same key on parameters?


Solution

  • The only way I made it work was altering the httpBody of the request.

        var requestBody = "{"
        for (_, value) in allText {
            requestBody.append("\'q\':\'\(value)\',")
        }
        requestBody.append("\'source\':\'\(Language.english.rawValue)\',")
        requestBody.append("\'target\':\'\(language.rawValue)\'")
        requestBody.append("}")
    
        var request = URLRequest(url: url!)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
    

    And performing the request with Alamofire worked for me.

    I don't really know why someone who can't provide a solution downvotes a question, but whatever, and hope will help someone who may run into similar task.