Sample code for 30+ languages & platforms
Swift

Google Translate Text

See more Google Translate Examples

Demonstrates how to use the Cloud Translation API to translate text from one spoken language to another. The example translates from English to Spanish.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // --------------------------------------------------------------------------------
    // IMPORTANT: 
    // Don't forget you need to 1st enable the Cloud Translation API in your Google Developers Console at https://console.cloud.google.com
    // --------------------------------------------------------------------------------

    // It is assumed we previously obtained an OAuth2 access token.
    // This example loads the JSON access token file 
    let jsonToken = CkoJsonObject()!
    success = jsonToken.loadFile(path: "qa_data/tokens/_googleTranslate.json")
    if success != true {
        print("Failed to load _googleTranslate.json")
        return
    }

    let http = CkoHttp()!

    http.authToken = jsonToken.string(of: "access_token")

    // The following JSON is sent in the request body.

    // {
    //     "q": "The quick brown fox jumped over the lazy dog.",
    //     "source": "en",
    //     "target": "es",
    //     "format": "text"
    // }

    let json = CkoJsonObject()!
    // The following code creates the JSON request body.
    json.updateString(jsonPath: "q", value: "The quick brown fox jumped over the lazy dog.")
    json.updateString(jsonPath: "source", value: "en")
    json.updateString(jsonPath: "target", value: "es")
    json.updateString(jsonPath: "format", value: "text")

    json.emitCompact = false
    print("\(json.emit()!)")

    let resp = CkoHttpResponse()!
    success = http.httpJson(verb: "POST", url: "https://translation.googleapis.com/language/translate/v2", json: json, contentType: "application/json", response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    let jResp = CkoJsonObject()!
    resp.getBodyJson(json: jResp)
    jResp.emitCompact = false

    print("Response Body:")
    print("\(jResp.emit()!)")

    var respStatusCode: Int = resp.statusCode.intValue
    print("Response Status Code = \(respStatusCode)")
    if respStatusCode >= 400 {
        print("Response Header:")
        print("\(resp.header!)")
        print("Failed.")
        return
    }

    // Sample JSON response:
    // (Sample code for parsing the JSON response is shown below)

    // {
    //   "data": {
    //     "translations": [
    //       {
    //         "translatedText": "El zorro r�pida salt� sobre el perro perezoso."
    //       }
    //     ]
    //   }
    // }

    var translatedText: String?

    var i: Int = 0
    var n: Int = jResp.size(ofArray: "data.translations").intValue
    while i < n {
        jResp.i = i
        translatedText = jResp.string(of: "data.translations[i].translatedText")
        print("\(translatedText!)")
        i = i + 1
    }


}