Why doesn't CFStringEncodings have UTF8 in Swi

2020-03-26 05:20发布

问题:

I am trying to create a percent encoded string in Swift so I can safely send text as a GET request. I found some Objective C code which I am trying to convert to Swift. I've written the following Swift code:

CFURLCreateStringByAddingPercentEscapes(nil, 
    CFStringRef(encodedString), nil, 
    CFStringRef("/%&=?$#+-~@<>|\\*,.()[]{}^!"), 
    kCFStringEncodingUTF8)

There is no kCFStringEncodingUTF8 in Swift ... If you right click the CFStringEncodings source you see there is a million things in there but no UTF8. I don't understand. How can I use the UTF8 string encoding in this situation?

EDIT : I found a way to encode a string but I still don't understand what happened to kCFStringEncodingUTF8

回答1:

The UTF-8 string encoding is defined as

enum CFStringBuiltInEncodings : CFStringEncoding {
    // ...
    case UTF8 /* kTextEncodingUnicodeDefault + kUnicodeUTF8Format */
    // ...
}

and can be used as

let orig = "a/b(c)"
let escaped = CFURLCreateStringByAddingPercentEscapes(nil, orig, nil,
    "/%&=?$#+-~@<>|\\*,.()[]{}^!",
    CFStringBuiltInEncodings.UTF8.rawValue)
println(escaped)
// a%2Fb%28c%29

As mentioned by @Zaph in a comment, stringByAddingPercentEncodingWithAllowedCharacters might be easier to use:

let charset = NSCharacterSet(charactersInString: "/%&=?$#+-~@<>|\\*,.()[]{}^!").invertedSet
let escaped = orig.stringByAddingPercentEncodingWithAllowedCharacters(charset)

or use one of the pre-defined character sets from Creating a Character Set for URL Encoding.



回答2:

kCFStringEncodingUTF8 has been replace in Swift with: UTF8.

There is a new NSString method added in iOS7 that takes a character set and a number of specialized character sets have been added and of course you can create specialized character sets. There is very little reason to use CFURLCreateStringByAddingPercentEscapes any more. See this: SO Answer