4

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

0

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Instead of using toRaw() we now have to use: CFStringBuiltInEncodings.UTF8.rawValue
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.