【问题标题】:Urlencode cyrillic characters in SwiftUrlencode Swift 中的西里尔字符
【发布时间】:2018-02-19 07:23:43
【问题描述】:

我需要使用 Windows-1251 编码将西里尔文字符串转换为其 urlencoded 版本。对于以下示例字符串:

Моцарт

正确的结果应该是:

%CC%EE%F6%E0%F0%F2

我尝试了addingPercentEncoding(withAllowedCharacters:),但它不起作用。

如何在 Swift 中达到想要的结果?

【问题讨论】:

    标签: swift string urlencode url-encoding cyrillic


    【解决方案1】:

    NSString 有一个 addingPercentEscapes(using:) 方法,它允许指定任意 编码:

    let text = "Моцарт"
    if let encoded = (text as NSString).addingPercentEscapes(using: String.Encoding.windowsCP1251.rawValue) {
        print(encoded)
        // %CC%EE%F6%E0%F0%F2
    }
    

    但是,自 iOS 9/macOS 10.11 起,已弃用。它会导致编译器警告,并且可能在较新的操作系统版本中不可用。

    您可以做的是将字符串 do Data 转换为 所需的编码, 然后将每个字节转换为相应的%NN 序列(使用来自 How to convert Data to hex string in swift):

    let text = "Моцарт"
    if let data = text.data(using: .windowsCP1251) {
        let encoded = data.map { String(format: "%%%02hhX", $0) }.joined()
        print(encoded)
        // %CC%EE%F6%E0%F0%F2
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-18
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 2011-12-06
      • 2010-09-29
      相关资源
      最近更新 更多