0

For work we have a third party company which supply a JSON api for some functionality. The JSON contains urls which I try to map in my code with URL(string: ...) but this fails on some urls which have spaces.

For example:

var str = "https://google.com/article/test test.html"

let url = URL(string: str) //nil

Should I ask the third party to encode their URLs ?

Is this normal or should I try to add encoding myself? Encoding myself is hard I think because the path should be encoded different from the query and the host shouldn't be encoded etc.

Or am I overthinking this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Haagenti
  • 7,974
  • 5
  • 38
  • 52

2 Answers2

1

If the URL contains spaces in its path, escape the characters with addingPercentEncoding(withAllowedCharacters passing the urlPathAllowed character set:

let str = "https://google.com/article/test test.html"
if let escapedString = str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed),
    let url = URL(string:escapedString) {
    print(url)
} else {
    print("url \(str) could not be encoded")
}
vadian
  • 274,689
  • 30
  • 353
  • 361
-1

What I would do if I were you, is to split the string up on the space, try converting each of the elements to a url, and when that works save it in your variable.

var str = "https://google.com/article/test test.html"
var url: URL? = nil
for urlString in str.components(separatedBy: .whitespacesAndNewlines) {
    let url = URL(string: urlString)
    if url != nil {
        break
    }
}
// url might be nil here, so test for value before using it

If each URL that you get from the API is in the format in your example, you can instead just grab the first element after spitting the string.

var str = "https://google.com/article/test test.html"
if let urlString = str.components(separatedBy: .whitespacesAndNewlines).first {
    let url = URL(string: urlString)
}
// url might be nil here, so test for value before using it
Nathan Ansel
  • 376
  • 3
  • 10
  • The specified URL is the correct URL. The space could be a %20 and it would be fine. Your answer would maybe give me an url but not the correct one. – Haagenti Jul 10 '17 at 21:00
  • @ScareCrow you can split strings on string values as well, so you could split on "%20" instead. – Nathan Ansel Jul 10 '17 at 21:03