基金会的字符串编码不是网站所期望的

时间:2016-08-04 12:55:54

标签: swift url networking encoding foundation

具体来说,它将变音符号编码为两个字符。

let unencoded = "könnten"
let encoded = unencoded.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

encoded等于ko%CC%88nnten。因此,它正在将ö转换为o%CC%88。所以它非常像,其中变音符号(¨)和o是分开的。

但是,大多数网站似乎都希望编码为%C3%B6,即ö,其中变音符号(¨)和o是一个单一字符。

您可以在此处看到编码不起作用的示例(Foundation如何对其进行编码):

https://www.linguee.com/german-english/search?query=ko%CC%88nnten

理想情况如何:

https://www.linguee.com/german-english/search?query=k%C3%B6nnten

有更好的方法来编码吗?也许是不同的选择或不同的框架?

1 个答案:

答案 0 :(得分:1)

理想情况下,服务器应该处理预先组合和分解 字符串。但是如果有必要,你可以预先编写字符串 客户方:

let unencoded = "könnten"
let encoded = unencoded.precomposedStringWithCanonicalMapping
        .stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())!

print(encoded) // k%C3%B6nnten

参见Technical Q&A QA1235 – Converting to Precomposed Unicode 了解更多信息。