Swift Components.Url 返回错误的 URL

Mar*_*Doe 3 xcode swift nsurlcomponents xcode14

我实现了以下代码,我可以在其中传递资源名称,它应该为我提供 URL。我正在使用 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
            
        }
Run Code Online (Sandbox Code Playgroud)

我将资源名称传递为“my-pets”,它应该返回,http://localhost:8080/my-pets但它不断返回http://my-pets。我不确定我在哪里犯了错误。

Rob*_*ier 5

您将“localhost:8080”作为主机名传递。这是不正确的。主机名是“localhost”。8080进入现场port

您可能想改用这种方法:

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

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

如果问题真的这么简单,你也可以这样做:

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

func resource(for resourceName: String) -> URL? {
    baseURL.appending(path: resourceName)
}
Run Code Online (Sandbox Code Playgroud)