SWIFT URL字符串构建

时间:2017-08-03 17:08:37

标签: swift xcode url

如何构建URL如下:

/sap/opu/odata/SAP/ZTM_FOR_MOBILITY_SRV/BusinessPartnerSet('BP-CR-EM01')/?$format=json

我特别想要这个部分 - BusinessPartnerSet(' BP-CR-EM01')。

BP-CR-EM01值是动态值。

let newUrl = url  + "'\(businessPartners[myIndex].partnerId)'"

url具有固定的URL和+运算符,后跟动态值。请帮我提一下你的建议。

1 个答案:

答案 0 :(得分:4)

我建议使用URLComponents

var components = URLComponents(string: "http://mycompany.com")!
components.path = "/sap/opu/odata/SAP/ZTM_FOR_MOBILITY_SRV/BusinessPartnerSet('\(businessPartners[myIndex].partnerId)')/"
components.queryItems = [URLQueryItem(name: "$format", value:"json")]
if let url = components.url {
    print(url)
    // or if you need the string
    print(url.absoluteString)
}