0

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.

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

Not working. My string is "sdfT&*w5e#sto([+peW7)%y9pqf])". I want to encode this.
@VamshiKrishna: Updated!
It worked. But with a minor update. Replacing "! '=();@&+$%#" by "! '=()[];@&+$%#". Thanks

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.