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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With