我正在尝试使用网络服务将阿拉伯语翻译成英语。构造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)")
}
但不幸的是,它打印
捕获错误urlParsingError(输出网址)
另外,我的结构看起来像[this](https://translate.yandex.net/api/v1.5/tr.json/translate?key= apikey& text =مرحبا& lang = en)
答案 0 :(得分:5)
您需要正确编码查询参数的值。一个好的解决方案是使用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)")
}
结果网址现在是:
答案 1 :(得分:2)
您必须对String进行编码才能获得有效的URL。您可以使用String.addingPercentEncoding(withAllowedCharacters: )
。
let jsonString = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20170517T154730Z.927d87b76de60242.7a92e4612778a4838d40ab192df5297d2a1af4ed&text=\(text)&lang=\(ToLan)"
guard let encodedJsonString = jsonString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: encodedJsonString) else {
throw MyErrors.urlParsingError(jsonString)
}
编码的网址变为: