Created
July 14, 2022 13:57
-
-
Save bubudrc/bdd99caa745309c015110718f15adecc to your computer and use it in GitHub Desktop.
Use Google Translate without API on Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private func getTranslationLanguage(translate: String, from originLanguage: String = "auto", to destinationLanguage: String = "en", completion: @escaping (_ result: String?) -> Void) { | |
// 1- Create the query | |
if let translatationURL: String = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=\(originLanguage)&tl=\(destinationLanguage)&dt=t&q= \(translate)&ie=UTF-8&oe=UTF-8".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), | |
let validURL = URL(string: translatationURL) { | |
var resultSearch: String = keyword | |
// 2- Make Request | |
URLSession.shared.dataTask(with: validURL) { [weak self] data, _, error in | |
guard error == nil, let data = data else { | |
assertionFailure("TRANSLATION ERROR: \(error.debugDescription)") | |
completion([]) | |
return | |
} | |
if let jsonString = String(data: data, encoding: .utf8) { | |
// 3- Get the response | |
let components = jsonString.components(separatedBy: "[") | |
if components.count > 3, // Added this validation to be sure that the index exist | |
let resultTemp = components[3] | |
.components(separatedBy: ",") | |
.first?.components(separatedBy: " ") | |
.first?.replacingOccurrences(of: "\"", with: "") { | |
completion(resultTemp) | |
return | |
} | |
completion(nil) | |
} else { | |
completion(nil) | |
} | |
}.resume() | |
} else { | |
completion(nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment