iosswiftswift4urlrequest

URL is nil or percentage encoded


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?


Solution

  • 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.