在Swift3 iOS10中替换CFURLCreateStringByAddingPercentEscapes?

时间:2017-03-20 08:13:33

标签: ios swift

我知道方法CFURLCreateStringByAddingPercentEscapes在iOS10中已弃用,它建议我使用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
    }
}

1 个答案:

答案 0 :(得分:2)

我担心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