regina_fallangi
regina_fallangi

Reputation: 2198

Add section to URL in swift

A URL can have a #sectionName component, which directs to the part of the site where that section begins.

In Swift I am trying to add that component, but it does not work. I am trying:

let url = URL(string: "example.com/component1")!

Later I am trying to do:

url.appendingPathComponent("#sectionName")

but it returns example.com/component1%23sectionName instead of example.com/component1#sectionName.

At the time the URL is created I still don't have the name of the section, so I can't do URL(string: "example.com/component1#sectionName")

I've also tried escaping the # with \# or \\#, but it does not work. Any ideas how to add a component that is a section?

Upvotes: 1

Views: 939

Answers (2)

Andy Ibanez
Andy Ibanez

Reputation: 12254

When building URLs, I recommend you use (NS)URLComponents instead of manually.

var components = URLComponents()
components.scheme = "https"
components.host = "example.com"
components.path = "/component1"
components.fragment = "sectionName"

let url = components.url

Upvotes: 2

OOPer
OOPer

Reputation: 47896

Your #sectionName component is not a path component and you cannot use appendingPathComponent.

You may need to use URLComponent and add fragment:

var urlCompo = URLComponents(string: "example.com/component1")!
urlCompo.fragment = "sectionName"
let url = urlCompo.url!
print(url) //->example.com/component1#sectionName

Upvotes: 2

Related Questions