SWIFT Translator App

坚强是说给别人听的谎言 提交于 2019-12-13 05:06:38

问题


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.

The API documentation says:

"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 documentation https://tech.yandex.ru/translate/doc/dg/reference/detect-docpage/


回答1:


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


来源:https://stackoverflow.com/questions/52016284/swift-translator-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!