Vamshi Krishna
Vamshi Krishna

Reputation: 989

String encoding - Swift

I am using the following method to encode a string in objective - C:

+(NSString*)urlEncoded:(NSString*)string
{ return ((NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes (NULL,(CFStringRef)string, NULL,(CFStringRef)@"! '=();@&+$%#",kCFStringEncodingUTF8 )));}

Is there any counterpart for this method in Swift 2.0 ? I have tried using many solutions present on stack, but none of them could solve my problem.

Upvotes: 0

Views: 1037

Answers (1)

Nate Cook
Nate Cook

Reputation: 93296

You probably want to use stringByAddingPercentEncodingWithAllowedCharacters with NSCharacterSet's URL-component specific character sets:

let title = "NSURL / NSURLComponents"
let escapedTitle = title.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

The idea behind those character sets is that they're probably more correct for the uses they describe than any finite set you have. That said, you could use the same method with a set you generate yourself:

let escapeSet = NSCharacterSet(charactersInString: "! '=();@&+$%#")
let string =  "sdfT&*w5e#sto([+peW7)%y9pqf])"
let escapedString = string.stringByAddingPercentEncodingWithAllowedCharacters(escapeSet.invertedSet)
// "sdfT%26*w5e%23sto%28[%2BpeW7%29%25y9pqf]%29"

Upvotes: 2

Related Questions