Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 899
Mary Doe Avatar asked Dec 13 '25 22:12

Mary Doe


1 Answers

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)
}
like image 68
Rob Napier Avatar answered Dec 16 '25 15:12

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!