【问题标题】:SWIFT Translator AppSWIFT 翻译应用程序
【发布时间】:2018-08-25 10:20:46
【问题描述】:

我使用 Yandex api 创建翻译器。 我使用这个功能:

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()
}

但是如果我在“文本”中输入更多一个单词,则不会进行翻译。

API 文档说:

"对于源代码,请务必使用 URL-encoding。"

我怀疑我的问题与我只使用文本而不以任何方式对其进行编码的事实有关。 这个问题怎么解决?

api 文档 https://tech.yandex.ru/translate/doc/dg/reference/detect-docpage/

【问题讨论】:

标签: ios swift yandex-api


【解决方案1】:

在这种情况下强烈建议使用URLComponentsURLQueryItem,它会隐式处理 URL 编码

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!)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-05
    • 2013-12-05
    • 2013-04-17
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 2018-05-01
    相关资源
    最近更新 更多