SWIFT翻译器应用程序 [英] SWIFT Translator App
本文介绍了SWIFT翻译器应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Yandex API创建翻译器. 我使用此功能:
I create translator using Yandex api. I use this function:
func getTranslate(text: String, lang: String, completion: @escaping (Translation?) -> Void) {
guard let url = URL(string: translateUrl + "?key=\(key)&text=\(text)&lang=\(lang)&format=plain&options=1") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print(error.localizedDescription)
completion(nil)
return
}
guard let data = data else {
completion(nil)
return
}
do {
let translation = try JSONDecoder().decode(Translation.self, from: data)
completion(translation)
} catch {
print(error)
completion(nil)
}
}.resume()
}
但是,如果我在文本"中输入更多内容,则不会进行一个单词的翻译.
But if I enter in "Text" more one word translation is not carried out.
API文档说:
对于源代码,请确保使用URL编码."
"For the source code, be sure to use URL-encoding."
我怀疑我的问题与我只使用文本而不以任何方式编码的事实有关. 该问题如何解决?
I suspect that my problem is related to the fact that I just use the text, not coding it in any way. How can this problem be solved?
api文档 https://tech.yandex.ru/translate/doc/dg/reference/detect-docpage/
推荐答案
在这种情况下,强烈建议使用URLComponents
和URLQueryItem
,它隐式处理URL编码
In this case it's highly recommended to use URLComponents
and URLQueryItem
, it handles URL encoding implicitly
guard var components = URLComponents(string: translateUrl) else { return }
components.queryItems = [URLQueryItem(name: "key", value: key),
URLQueryItem(name: "text", value: text),
URLQueryItem(name: "lang", value: lang),
URLQueryItem(name: "format", value: "plain"),
URLQueryItem(name: "options", value: String(1))]
var request = URLRequest(url: components.url!)
这篇关于SWIFT翻译器应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文