swiftxcodensurlcomponentsxcode14

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.


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)
    }