Swift
Swift
Amazon Translate Text
See more AWS Translate Examples
Demonstrates how to use the AWS Translate service to translate text from one language to another.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
let rest = CkoRest()!
let authAws = CkoAuthAws()!
authAws.accessKey = "AWS_ACCESS_KEY"
authAws.secretKey = "AWS_SECRET_KEY"
authAws.region = "us-west-2"
authAws.serviceName = "translate"
rest.setAuthAws(authProvider: authAws)
// URL: https://translate.us-west-2.amazonaws.com/
var bTls: Bool = true
var port: Int = 443
var bAutoReconnect: Bool = true
success = rest.connect(hostname: "translate.us-west-2.amazonaws.com", port: port, tls: bTls, autoReconnect: bAutoReconnect)
if success != true {
print("ConnectFailReason: \(rest.connectFailReason.intValue)")
print("\(rest.lastErrorText!)")
return
}
// Translate text from English to German
let json = CkoJsonObject()!
json.updateString(jsonPath: "SourceLanguageCode", value: "en")
json.updateString(jsonPath: "TargetLanguageCode", value: "de")
json.updateString(jsonPath: "Text", value: "This is the text to be translated")
rest.addHeader(name: "Content-Type", value: "application/x-amz-json-1.1")
rest.addHeader(name: "X-Amz-Target", value: "AWSShineFrontendService_20170701.TranslateText")
let sbRequestBody = CkoStringBuilder()!
json.emitSb(sb: sbRequestBody)
let sbResponseBody = CkoStringBuilder()!
success = rest.fullRequestSb(httpVerb: "POST", uriPath: "/", requestBody: sbRequestBody, responseBody: sbResponseBody)
if success != true {
print("\(rest.lastErrorText!)")
return
}
var respStatusCode: Int = rest.responseStatusCode.intValue
if respStatusCode >= 400 {
print("Response Status Code = \(respStatusCode)")
print("Response Header:")
print("\(rest.responseHeader!)")
print("Response Body:")
print("\(sbResponseBody.getAsString()!)")
return
}
let jsonResponse = CkoJsonObject()!
jsonResponse.loadSb(sb: sbResponseBody)
jsonResponse.emitCompact = false
print("\(jsonResponse.emit()!)")
// {
// "SourceLanguageCode": "en",
// "TargetLanguageCode": "de",
// "TranslatedText": "Dies ist der zu �bersetzende Text"
// }
print("\(jsonResponse.string(of: "TranslatedText")!)")
}