1

I tried to call a custom url using this code below:

let myurl = "https://myserver.com/call?a|b|c"
let converted = URL(string: myurl)
print(converted)

But what I'm getting as result in converted is just "nil".


I'm pretty sure this is because of the wrong characters set in relation to the URL() class.

After some research all I got so far is this outdated Swift code:

var myurl = "https://myserver.com/call?a|b|c"
var newurl = myurl.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
print(newurl)

But it doesn't seems working this way.

How can I achieve to avoid the "nil" result using (in my case) Swift 4?

Jonas0000
  • 1,085
  • 1
  • 12
  • 36

1 Answers1

0

Found the solution on my own:

let myurl = "https://myserver.com/call?a|b|c"
let converted = URL(string: myurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)

print(converted!)


The new function is called addingPercentEncoding & I have to call it with the urlQueryAllowed property.

The urlQueryAllowed charset adds some characters like this to the url encoding: "!*'();:@&=+$,/?%#[]|"

VoliĆ !

Jonas0000
  • 1,085
  • 1
  • 12
  • 36