The server returns a gb2312 string that has been processed by the urlencode function:
%D7%CF%BD%FB%B3%C7%C4%A7%D6%E4_%CE%DE%CF%DE%D0%A1%CB%B5%CD%F8_www.55x.cn.rar
How to decode it back to gb2312 string:
紫禁城魔咒_无限小说网_www.55x.cn.rar
NSString does include this functionality in a deprecated function.
https://developer.apple.com/documentation/foundation/nsstring/1407783-replacingpercentescapes
OOPer's answer is great. recently I met this issue too and found this post. I came up with a function to do the reversed operation. hope it will help someone else.
func urlencode(using encoding: String.Encoding = .gb_18030_2000) -> String? {
var res = ""
let allowedSet = NSMutableCharacterSet()
allowedSet.formUnion(with:CharacterSet.urlQueryAllowed)
// I need to filter the `&` char as well. change it for your needs.
allowedSet.removeCharacters(in: "&")
let allowed = allowedSet as CharacterSet
if let data = src.data(using: encoding) {
res = data.reduce(into:res) {
let scalar = UnicodeScalar($1)
if $1 <= 127, allowed.contains(scalar) {
$0 += String(Character(scalar))
} else {
$0 += String(format:"%%%02X", $1)
}
}
}
return res.isEmpty ? self : res
}
Percent encoding on other encodings than UTF-8 is not considered to be a recommended way in recent www world, so you may need to implement such conversion by yourself.
It may be something like this: