gpt4 book ai didi

ios - 阿拉伯文本的 URL 解析错误

转载 作者:搜寻专家 更新时间:2023-11-01 05:52:08 25 4
gpt4 key购买 nike

我正在尝试使用网络服务将阿拉伯语翻译成英语。构建 URL 时出现错误。我定义了这些情况:

enum MyErrors: Error {
case urlParsingError(String)
case nonDictonaryObjectReturned(Any)
}

我的代码是:

func translateWord (text: String, ToLan:String) {

// the text is "مرحبا" and ToLan is "en"

do {
let jsonString = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=apikey&text=\(text)&lang=\(ToLan)"

guard let url = URL(string: jsonString) else {
throw MyErrors.urlParsingError(jsonString)
}

let data = try Data(contentsOf: url, options: Data.ReadingOptions())

let jsonObject = try JSONSerialization.jsonObject(with: data,options: .allowFragments)
guard let dictionary = jsonObject as? [AnyHashable: Any] else {
throw MyErrors.nonDictonaryObjectReturned(jsonObject)
}
let result = dictionary["text"] as? [Any]
let translattedSTR = result?.first as? String
let encodedData = translattedSTR?.data(using: String.Encoding.utf8)!
print(encodedData!)
self.textresult.text = translattedSTR


} catch {
print("caught error \(error)")
}

但不幸的是,它打印了

caught error urlParsingError(output url)

此外,我的结构看起来像 [this]( https://translate.yandex.net/api/v1.5/tr.json/translate?key= apikey&text=مرحبا&lang=en)

最佳答案

您需要正确编码查询参数的值。一个好的解决方案是使用 URLComponents 来构建您的查询。

然后是这些行:

let jsonString = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=myAPIkey&text=\(text)&lang=\(ToLan)"

guard let url = URL(string: jsonString) else {
throw MyErrors.urlParsingError(jsonString)
}

需要替换为:

let baseString = "https://translate.yandex.net/api/v1.5/tr.json/translate"
var comps = URLComponents(string: baseString)!
let keyQuery = URLQueryItem(name: "key", value: "myAPIKey")
let textQuery = URLQueryItem(name: "text", value: text)
let langQuery = URLQueryItem(name: "lang", value: ToLan)
comps.queryItems = [ keyQuery, textQuery, langQuery ]
guard let url = comps.url else {
throw MyErrors.urlParsingError("\(comps)")
}

现在生成的 url 是:

https://translate.yandex.net/api/v1.5/tr.json/translate?key=myAPIkey&text=%D9%85%D8%B1%D8%AD%D8%A8%D8%A7&lang=en

关于ios - 阿拉伯文本的 URL 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47251259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com