如何防止 URLComponents().port 在查询前添加问号 (Swift/Xcode)

man*_*nto 0 swift nsurlcomponents

我正在尝试URLComponents()在我设计的应用程序中组成一个代表。

这是代码:

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    var components = URLComponents()

    components.scheme = "http"
    components.host = "0.0.0.0"
    components.port = 9090
    let queryItemToken = URLQueryItem(name: "/predict?text", value: "what's your name?")
    components.queryItems = [queryItemToken]

    print(components.url as Any)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是上述代码段的输出:

Optional(http://0.0.0.0:9090?/predict?text=what's%20your%20name?)
Run Code Online (Sandbox Code Playgroud)

由于 ? 在端口和查询之间!我怎样才能防止URLComponents()插入这个多余的?在端口和查询之间!

目标输出: Optional(http://0.0.0.0:9090/predict?text=what's%20your%20name?)

rma*_*ddy 5

/predict部分是path,而不是查询项。text是实际的查询参数。

你要:

var components = URLComponents()
components.scheme = "http"
components.host = "0.0.0.0"
components.port = 9090
components.path = "/predict"
let queryItemToken = URLQueryItem(name: "text", value: "what's your name?")
components.queryItems = [queryItemToken]
print(components.url!)
Run Code Online (Sandbox Code Playgroud)