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.
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)")!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With