如何在Swift中查看将数据发布到Yandex API的响应

时间:2019-04-09 02:43:49

标签: ios json swift api yandex-api

我正在尝试使用以下方法将一些文本发布到Yandex翻译api,但似乎会找回无效的JSON。但是,我看不懂我要回来的东西。有没有办法解析“数据”?这是方法

func getTranslated(text: String, lang: "en-fr", completion: @escaping (TranslationReturned?) -> Void) {
        guard var components = URLComponents(string: translationUrl) else { return }
        components.queryItems = [URLQueryItem(name: "key", value: translationKey),
                                 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!)

          request.httpMethod = "POST"

        URLSession.shared.dataTask(with: request) { (data, response, error) in
            print("data in call to yandex is",data as Any)//79 bytes
            if let error = error {
                print("error is",error.localizedDescription)
                completion(nil)
                return
            }

            guard let data = data else {
                print("no data")
                completion(nil)
                return
            }

            do {
                let translation = try JSONDecoder().decode(TranslationReturned.self, from: data)
                completion(translation)
            } catch {
                print(error)
                completion(nil)
            }
            }.resume()
    }

返回的项目长79个字节,错误为nil,但我无法确定是什么数据。这是调试器显示的内容:

data in call to yandex is Optional(79 bytes)
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "code", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))
(lldb) po data

error: <EXPR>:3:1: error: use of unresolved identifier 'data'; did you mean 'Data'?
data

编辑:

这是TransationReturned对象的外观:

@objc public class TranslationReturned: NSObject, Codable {
    var code: String = ""
    var lang: String = ""
    var text: String = ""
}

编辑2

强制转换为rmaddy建议的字符串后返回JSON:

{"code":200,"detected":{"lang":"en"},"lang":"en-fr","text":["Bonjour les ami"]}

我能够通过将TranslationReturned更改为处理JSON的结构来解决错误,如下所示:

 @objc public class TranslationReturned: NSObject, Codable {
        var code: Int = 0
        var lang: String = ""
        var text = [String]()
        }

0 个答案:

没有答案