在 Swift 中,可以通过 URLComponents 类来解析 URL 中的查询字符串。
首先,将 URL 字符串转换为 URL 对象:
let urlString = "https://www.example.com/search?q=apple&category=fruit"
guard let url = URL(string: urlString) else {
fatalError("Invalid URL")
然后,使用 URLComponents 获取查询字符串中的参数:
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true),
let queryItems = components.queryItems else {
fatalError("Invalid URL components")
for queryItem in queryItems {
print("\(queryItem.name) = \(queryItem.value ?? "")")
在这个例子中,我们通过 URLComponents 获取了查询字符串中的参数,然后遍历这些参数并打印出每个参数的名称和值。
输出结果:
q = apple
category = fruit
需要注意的是,如果 URL 中没有查询字符串,components.queryItems
将返回 nil
。另外,如果查询字符串中有重复的参数名,queryItems
数组中将包含多个相同名称的查询项。