0

I need to create URL from string https://example.com/media/caffè.mp3

let url = URL(string: "https://example.com/media/caffè.mp3") // fails to create URL

But in Safari it works as expected.

How can I encode this string or something to get working URL from it?

Stany Miles
  • 212
  • 2
  • 12

2 Answers2

1

You can try this code:

let urlString = "https://example.com/media/caffè.mp3".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) 
let url = URL(string: urlString )
Son Pham
  • 1,516
  • 1
  • 14
  • 22
0
let urlString = "https://example.com/media/caffè.mp3"

let encoded = urlString
      .addingPercentEncoding(
        withAllowedCharacters: .urlQueryAllowed)!

let url = URL(string: encoded) // this works
Stany Miles
  • 212
  • 2
  • 12