当然它是免费的,您可以实现它(我在下面提供了一个示例)。但是,不要使用它,因为一段时间后 Google 可以检测到可疑流量——很遗憾,它发生在我身上——所以你会收到一条错误消息。我不确定在他们检测到您的活动之前您可以使用它多长时间,所以我对您的建议是使用“免费服务”广泛测试您的应用程序,如果您发现一些问题,也许您应该购买该服务或寻找其他服务API。https://api.mymemory.translated.net是一个免费但有限的替代方案。
在 iOS Swift 4 中,您可以使用以下函数实现免费服务:
func translate(str: String, lang1: String, lang2: String) {
let escapedStr = str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
let lastPart = lang1 + "&tl=" + lang2 + "&dt=t&dt=t&q=" + escapedStr!
let urlStr: String = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + lastPart
let url = URL(string: urlStr)
let task = URLSession.shared.downloadTask(with: url!) { localURL, urlResponse, error in
if let localURL = localURL {
if let string = try? String(contentsOf: localURL) {
let index = string.firstIndex(of: "\"")
let index2 = string.index(after: index!)
let subst = string.substring(from: index2)
let indexf = subst.firstIndex(of: "\"")
let result = subst.substring(to: indexf!)
DispatchQueue.main.async {
if flag1country != flag2country {
self.texto.text = result
}
}
}
}
}
task.resume()
}
(也许这不是最好的实现,但它有效)。