解析基于URL路径的rest API

问题描述:

我使用REST API创建客户端应用程序。这一个使用URL路径格式,即/api/subPath/{variable}/otherSubPath解析基于URL路径的rest API

我知道苹果给出了一个URLComponents类,但似乎只针对URL-query-argument/api/path?param=value

工作得很好,我想创建一个类URLBuilder给我不同API网址动态。目前我结束了一类谁是这样的:

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

您是否使用URLappend...系列函数进行了研究?

如果我理解你的要求,你可以这样做:

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

输出:api/subPath/variable/otherSubPath

如果您需要一条线,您甚至可以将appending调用链接在一起。