您好,我尝试将queryItems添加到我的URLComponents中,但是由于URLQueryItem返回其值作为可选值,因此该URL中始终带有问号。
var params = ["id":"5"]
let queryParams = toStringDictionary(dictionary: params).map { pair in
return URLQueryItem(name: pair.key, value: pair.value)
}
var components = URLComponents(string: fullURL)
components.queryItems = queryParams
print(components.url)//This is the full url https://demo.com/users/?5
//This https://demo.com/users/?5 should be this https://demo.com/users/5
问号当然会导致网址错误。我无法摆脱它。
答案 0 :(得分:6)
查询参数与网址的其余部分之间用问号分隔,例如:
https://example.com/path?param_name=param_value
问号不是可选的,而是提供查询参数的方式。
您评论中的示例似乎失去了参数的名称,我希望它能读取
https://demo.com/users/?id=5
如果它绝对不包含id=
位,请您分享一下toStringDictionary
的实现,以便我们可以看到发生了什么吗?您传入的字典已经是一个字符串字典,因此具有这种功能似乎很奇怪。
编辑:按照您的说明(现在已经消失了,但很清楚,您希望添加到路径而不是查询字符串中)
您的代码似乎正确添加了查询参数;仔细查看它产生的URL,它将为https://demo.com/users/?id=5
。查询参数不是路径的一部分,它们位于末尾,并与URL的其余部分之间用?
从您的编辑看来,您实际上真正想要做的是添加到URL的路径,以便获得https://demo.com/users/5
。该URL没有任何查询参数,因此URLQueryItem
是作业的错误工具。
要添加到路径,您可以执行以下操作:
let userID = "5"
let url = URL(string: "https://example.com/users")!
let newUrl = url.appendingPathComponent(userID)
print(newUrl.absoluteString) //https://example.com/users/5
NB-在本示例中,为简洁起见,仅强制展开url
,因为已知传递给URL()的字符串是有效的。在实际使用中,您应该更加谨慎地对待可选件。
答案 1 :(得分:1)
您的let fullURL = "https://demo.com/users/"
假设
let queryParams = params.map{ URLQueryItem(name: $0, value: $1) }
var components = URLComponents(string: fullURL)!
components.queryItems = queryParams
print(components.url!)
// https://demo.com/users/?id=5
您需要做的只是...
TypeBuilder.CreateType
请注意,在实践中应避免力解开