Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift Components.Url is Returning the Wrong URL

I implemented the following code, where I can pass in the name of the resource and it should give me the URL. I am using Xcode 14 Beta 3.

 static let baseUrl = "localhost:8080"
 static func resource(for resourceName: String) -> URL? {
            
            var components = URLComponents()
            components.scheme = "http"
            components.percentEncodedHost = baseUrl
            components.path = "/\(resourceName)"
            return components.url
            
        }

I am passing a resource name as ‘my-pets’ and it is supposed to be returning http://localhost:8080/my-pets but it keeps returning http://my-pets. I am not sure where I am making a mistake.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re passing "localhost:8080" as a hostname. This isn’t correct. The hostname is "localhost". 8080 goes in the port field.

You may want to use this approach instead:

let baseURL = URLComponents(string: "http://localhost:8080")!

func resource(for resourceName: String) -> URL? {
    var components = baseURL
    components.path = "/\(resourceName)"
    return components.url
}

You might also do it this way, if the problem is really this simple:

let baseURL = URL(string: "http://localhost:8080")!

func resource(for resourceName: String) -> URL? {
    baseURL.appending(path: resourceName)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading