代码之家  ›  专栏  ›  技术社区  ›  user8844576

阿拉伯语文本的URL分析错误

  •  1
  • user8844576  · 技术社区  · 7 年前

    我正在尝试使用web服务将阿拉伯语翻译成英语。我在构建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(输出url)

    此外,我的结构看起来像[这个]( https://translate.yandex.net/api/v1.5/tr.json/translate?key= apikey&文本=±¨§&lang=en)

    2 回复  |  直到 7 年前
        1
  •  5
  •   rmaddy    7 年前

    您需要正确编码查询参数的值。一个好的解决方案是使用 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

        2
  •  2
  •   Dávid Pásztor    7 年前

    您必须对字符串进行编码才能获得有效的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)
    }
    

    编码的URL变为:

    https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20170517T154730Z.927d87b76de60242.7a92e4612778a4838d40ab192df5297d2a1af4ed&text=%D9%85%D8%B1%D8%AD%D8%A8%D8%A7&lang=en