Swift – encode URL

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it doesn’t escape the slashes /.

I’ve searched and found this Objective C code:

NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                        NULL,
                        (CFStringRef)unencodedString,
                        NULL,
                        (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                        kCFStringEncodingUTF8 );

Is there an easier way to encode an URL and if not, how do I write this in Swift?

19 Answers
19

Leave a Comment