Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't CFStringEncodings have UTF8 in Swift?

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

like image 906
Johnston Avatar asked Dec 08 '22 06:12

Johnston


2 Answers

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.

like image 193
Martin R Avatar answered Dec 11 '22 09:12

Martin R


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

like image 28
zaph Avatar answered Dec 11 '22 07:12

zaph