我需要在swift中创建一个URL,路径中带有编码的斜杠(没有层次意义)

我需要在swift中创建一个URL,路径中带有编码的斜杠(没有层次意义),swift,http,url,Swift,Http,Url,我的URL是这样的:https://domain.tld/path/question Thing1/Thing2 编码后,我希望我的url成为becmomehttps://domain.tld/path/question%20Thing1%20%2f%20Thing2 如果我这样做 var components=urlmonents() components.scheme=“https” components.host=“domain.tld” components.path=“路径/问题内容1

我的URL是这样的:
https://domain.tld/path/question Thing1/Thing2

编码后,我希望我的url成为becmome
https://domain.tld/path/question%20Thing1%20%2f%20Thing2

如果我这样做

var components=urlmonents()
components.scheme=“https”
components.host=“domain.tld”
components.path=“路径/问题内容1/2”
最后一个前言斜杠未编码,url变为
https://domain.tld/path/question%20Thing1%20%/20Thing2

如果我这样做:

components.path=“路径/问题内容1%2f内容2”
url变为
https://domain.tld/path/question%20Thing1%20%25%2f20Thing2

我明白为什么会发生这种情况,我只需要一个swift解决方案

import Foundation
let base = "https://domain.tld/path/question"
let path = " Thing1 / Thing2t"
let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let urlString  = "\(base)\(encodedPath)"
print(urlString)
输出:

https://domain.tld/path/Fquestion%20Thing1%20%2F%20Thing2t

有几种方法。如果您可以轻松地手工计算准确的编码,那么您可以使用
percentEncodedPath

var components = URLComponents()
components.scheme = "https"
components.host = "domain.tld"
components.percentEncodedPath = "/path/question%20Thing1%20%2f%20Thing2"
let url = URL(string: "https://domain.tld/path/\(filePath)")!
或者,您可以对“所有非路径字符+斜杠”进行编码:

然后加上:

var components = URLComponents()
components.scheme = "https"
components.host = "domain.tld"
components.path = "/path/"

components.percentEncodedPath += filePath
或者跳过组件并使用相同的
文件路径生成字符串:

var components = URLComponents()
components.scheme = "https"
components.host = "domain.tld"
components.percentEncodedPath = "/path/question%20Thing1%20%2f%20Thing2"
let url = URL(string: "https://domain.tld/path/\(filePath)")!

我不希望出现/后路径和前问题encoded@KabirKwatra更新了我的答案。你需要理解我所做的背后的逻辑。仔细查看path变量和下一行encodedPath。我试图对path变量中的所有内容进行编码。就像你在评论中说的,你不想在路径之后和问题之前编码斜杠,所以我把它移到了基变量。