-1

I have this URL

https://apps.apple.com/developer/john-doe/id32123123#see-all/mac-apps

I do this

let path = "https://apps.apple.com/developer/john-doe/id32123123#see-all/mac-apps"
let url = URL(string: path!)

the resulting url is nil.

I do this:

var components = URLComponents()
components.scheme = "https"
components.host = "apps.apple.com"
components.path = "/developer/john-doe/id32123123#see-all/mac-apps"

let url = components.url!

The resulting url percentage encoded, like this and, as expect, an URLRequest done with that URL fails.

https://apps.apple.com/developer/john-doe/id32123123%23see-all/mac-apps

Is there a way to get a normal URL without any percentage encoding?

How do I do a URL that works with URLRequest?

Duck
  • 34,902
  • 47
  • 248
  • 470
  • 4
    `let url = URL(string: path!)` does not compile because `path` is not an optional. When I remove the exclamation mark then the result is as expected. Can you post a [mcve]? – Martin R Sep 26 '19 at 13:31
  • 1
    It worked in Playground for me. – Larme Sep 26 '19 at 13:32
  • 3
    In your URLComponents example you should assign `components.fragment = "see-all/mac-apps"` instead of appending the fragment to the path. – Martin R Sep 26 '19 at 13:33
  • @MartinR and what about the #? – Duck Sep 26 '19 at 13:39
  • 1
    @SpaceDog The `#` marks the beginning of the url's fragment. It's a special character, which is why the system is percent-encoding it for you when you try to use it as part of the path. You should read up on the URL standard. – Alexander Sep 26 '19 at 13:41
  • 1
    @SpaceDog: You don't assign that separator to an URLComponent, like you also don't assign the `//` separater. – Martin R Sep 26 '19 at 13:42
  • @SpaceDog Exactly, like Martin said, the appropriate delimiting tokens are inserted for you when producing the final url (`://`, `#`, etc.). – Alexander Sep 26 '19 at 13:45
  • 1
    ... still waiting for the actual code that produces the `nil` URL ... – Martin R Sep 26 '19 at 13:50

1 Answers1

1

This code works just fine:

let path = "https://apps.apple.com/developer/john-doe/id32123123#see-all/mac-apps"
let url = URL(string: path)

I just had to remove the !. Path is not optional, so there's nothing to unwrap.

Your latter technique isn't something you should bother using for literal URLs like this, but I can explain why it's "not working" to your expectations anyway. The # marks the beginning of the url's fragment. It's a special character, which is why the system is percent-encoding it for you when you try to use it as part of the path. Here's the fixed code:

var components = URLComponents()
components.scheme = "https"
components.host = "apps.apple.com"
components.path = "/developer/john-doe/id32123123"
components.fragment = "see-all/mac-apps"
let url = components.url! // => "https://apps.apple.com/developer/john-doe/id32123123#see-all/mac-apps"

You should read up on the URL standard.

Alexander
  • 59,041
  • 12
  • 98
  • 151