我知道iOS10中已弃用CFURLCreateStringByAddingPercentEscapes
方法,建议我使用stringByAddingPercentEncodingWithAllowedCharacters
,但我不使用UTF-8,我如何使用stringByAddingPercentEncodingWithAllowedCharacters
来完成以下操作:
extension String {
var gbkEncoded: String {
let cfEnc = CFStringEncodings.GB_18030_2000
return CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, self as CFString!, nil, nil, CFStringEncoding(cfEnc.rawValue)) as String
}
}
最佳答案
恐怕Apple不会为我们提供CFURLCreateStringByAddingPercentEscapes
的替代品,因为在现代网络标准中不建议使用非UTF-8。
您可能需要自己做。一个例子:
extension CharacterSet {
static let rfc3986Unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
}
extension String.Encoding {
static let gb_18030_2000 = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)))
}
extension String {
func addingPercentEncoding(withAllowedCharacters characterSet: CharacterSet, using encoding: String.Encoding) -> String {
let stringData = self.data(using: encoding, allowLossyConversion: true) ?? Data()
let percentEscaped = stringData.map {byte->String in
if characterSet.contains(UnicodeScalar(byte)) {
return String(UnicodeScalar(byte))
} else if byte == UInt8(ascii: " ") {
return "+"
} else {
return String(format: "%%%02X", byte)
}
}.joined()
return percentEscaped
}
var gbkEncoded: String {
return self.addingPercentEncoding(withAllowedCharacters: .rfc3986Unreserved, using: .gb_18030_2000)
}
}
print("互联网".gbkEncoded) //->%BB%A5%C1%AA%CD%F8
关于ios - 在Swift3 iOS10中替代CFURLCreateStringByAddingPercentEscapes?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42898619/