Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to create a URL in swift with an encoded foreword slash in its path (without hierarchical significance)

Tags:

http

url

swift

My URL is something like this: https://domain.tld/path/question Thing1 / Thing2

When encoded, I want my url to becmome https://domain.tld/path/question%20Thing1%20%2f%20Thing2

If i do

var components = URLComponents()
components.scheme = "https"
components.host = "domain.tld"
components.path = "path/question Thing1 / Thing2"

the last foreword slash is not encoded, and the url becomes https://domain.tld/path/question%20Thing1%20%/20Thing2

if I do:

components.path = "path/question Thing1 %2f Thing2"

The url becomes https://domain.tld/path/question%20Thing1%20%25%2f20Thing2.

I understand why this happens, I just need a swift solution.

like image 819
Kabir Kwatra Avatar asked Sep 21 '25 01:09

Kabir Kwatra


1 Answers

There are several approaches. If you can easily compute the exact encoding by hand, then you can just use percentEncodedPath:

var components = URLComponents()
components.scheme = "https"
components.host = "domain.tld"
components.percentEncodedPath = "/path/question%20Thing1%20%2f%20Thing2"

Alternately, you can encode "all non-path characters + slash":

let allowedCharacters = CharacterSet.urlPathAllowed.subtracting(CharacterSet(charactersIn: "/"))
let filePath = "question Thing1 / Thing2".addingPercentEncoding(withAllowedCharacters: allowedCharacters)!

And then append that:

var components = URLComponents()
components.scheme = "https"
components.host = "domain.tld"
components.path = "/path/"

components.percentEncodedPath += filePath

Or skip the components and make a string with the same filePath:

let url = URL(string: "https://domain.tld/path/\(filePath)")!
like image 60
Rob Napier Avatar answered Sep 23 '25 05:09

Rob Napier