我正在使用 REST API 创建一个客户端应用程序。这个使用 URL 路径格式,即 /api/subPath/{variable}/otherSubPath
我知道苹果提供了一个 URLComponents
类,但似乎只适用于 URL-query-argument
即 /api/path?param=value
我想创建一个类 URLBuilder
来动态地为我提供不同的 API url。目前,我最终得到了一个如下所示的类:
class URLBuilder {
fileprivate static let base = "https://theAPI.com/"
fileprivate static let objectsPath = kBase + "objects/"
static func informationOfObject(withID id: Int) {
return objectsPath + "\(id)/" + "information/"
}
// Many other functions like this
}
所以我想知道如何获得更优雅的东西(如果可能的话),并且可能将 URL 路径格式与 URLComponents
一起使用。
或者也许我应该使用正则表达式?我从未使用过它,但也许它在这里很有用。
最佳答案
您是否考虑过使用 URL
中的 append...
系列函数?
- appendPathComponent(_:)
- appendPathComponent(_:isDirectory:)
- appendingPathComponent(_:)
- appendingPathComponent_:isDirectory:)
如果我了解您的要求,您可以执行以下操作:
let baseURL = URL(string: "/api/subPath")!
let variableURL = baseURL.appendingPathComponent("variable")
let trailingURL = variableURL.appendingPathComponent("otherSubPath")
print(trailingURL.absoluteString)
输出:api/subPath/variable/otherSubPath
如果您需要将其放在一行上,您甚至可以将appending
调用链接在一起。
关于swift - 解析基于 URL 路径的 Rest API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46698565/