我是Swift的新手,在将API字符串传递给URLSession之前,我正在按以下步骤构建API URL字符串。
我想知道有更好的方法吗?
let jsonUrlString = Constants.API_URL + "/" + Constants.PATH + "/"
+ String(page)+"/" + Constants.NUMBER_ITEMS_PER_PAGE
答案 0 :(得分:2)
构建URL的正确方法是使用URL
和URLComponents
。仅将字符串附加在一起很容易出错,并且不能正确地转义值中可能包含的特殊字符。
这是使用URL
的一种可能的解决方案:
if let baseURL = URL(string: Constants.API_URL) {
let jsonURL = baseURL.appendingPathComponent(Constants.PATH)
.appendingPathComponent(String(page))
.appendingPathComponent(Constants.NUMBER_ITEMS_PER_PAGE)
// use jsonURL with your URLSession
}
URLComponents
的另一个选项(这可以确保对特殊字符进行编码):
if let baseComps = URLComponents(string: Constants.API_URL) {
var components = baseComps
components.path = "/\(Constants.PATH)/\(page)/\(Constants.NUMBER_ITEMS_PER_PAGE)"
if let jsonURL = components.url {
// use jsonURL with your URLSession
}
}
答案 1 :(得分:1)
另外,还有一种快速构建字符串的方法称为插值,大多数情况下供开发人员使用。
如果使用此方法,则不必将Int或其他类型的值带入字符串,因为这是自动将值带入字符串。
即
let myValue = 3
let intToString = "\(myValue)" // "3"
let doubleValue = 4.5
let doubleToString = "\(doubleValue)" // "4.5"
因此您的网址将如下所示
let jsonUrlString = "\(Constants.API_URL)/\(Constants.PATH)/\(page)/\(Constants.NUMBER_ITEMS_PER_PAGE)"