2017-10-11 106 views
0

我使用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。 或者應該使用正則表達式?我從來沒有使用它,但也許在這裏很有用。

回答

0

您是否使用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調用鏈接在一起。