#06: URL/URI Escaping in Swift 3: Encoding and Decoding

The most straightforward way to escape URLs in Swift is to simply use one of the methods provided by NSString from Foundation:


import Foundation  

var original = "This/is a test"
var escaped = original.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
escaped!  //This%2Fis%20a%20test

There are a few default CharacterSet provided via static property to choose from, depending on the final destination of the encoded string:

Value Set Characters
.urlFragmentAllowed ”#%<>[]^`{|}
.urlHostAllowed ”#%/<>?@\^`{|}
.urlPasswordAllowed ”#%/:<>?@[]^`{|}
.urlPathAllowed ”#%;<>?[]^`{|}
.urlQueryAllowed ”#%<>[]^`{|}
.urlUserAllowed ”#%/:<>?@[]^`

Additionally, if you have a different use case in mind with a custom set of characters to escape, you can create your own character set specifying all the characters you need in a string:


var myCharset= CharacterSet("#%&")

And then, use it with addingPercentEncoding.

This short post is one of the Swift Bites, click the link for more!


This is the blog of Umberto Raimondi, you can reach me at me@this domain.

I'm also on Twitter and GitHub.

Subscribe via RSS or email.