代码之家  ›  专栏  ›  技术社区  ›  DEADBEEF

解析基于URL路径的rest API

  •  0
  • DEADBEEF  · 技术社区  · 9 年前

    /api/subPath/{variable}/otherSubPath

    URLComponents 但似乎只有在 URL-query-argument 即 /api/path?param=value

    我想创建一个类 URLBuilder

    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组件 或者我应该用正则表达式?我从来没有用过它,但也许它在这里有用。

    1 回复  |  直到 9 年前
        1
  •  0
  •   caseynolan    9 年前

    你考虑过使用 append... 函数族 URL ?

    如果我理解你的要求,你可以做以下事情:

    let baseURL = URL(string: "/api/subPath")!
    let variableURL = baseURL.appendingPathComponent("variable")
    let trailingURL = variableURL.appendingPathComponent("otherSubPath")
    print(trailingURL.absoluteString)
    

    输出: api/subPath/variable/otherSubPath

    你甚至可以把 appending 如果您需要,请在一条线上呼叫。

    推荐文章