在 Swift 中,URLComponents 是一个结构体,专门用于构建和解析 URL。可以创建和处理 URL 的各个部分(如协议、主机、路径、查询参数等),从而避免直接手动拼接 URL 字符串的麻烦。
例如,在处理URL Scheme字符串时:
myapp://open?id=123&type=photo
通常需要手动解析 ://、?、&等符号,并处理缺失的字段。
URLComponents可以设置协议、主机、路径、查询参数等属性,构造符合标准的 URL。并将 URL 字符串分解成各个部分,比如协议、主机、端口、路径、查询参数等,便于获取和修改这些信息。
构建方法
1、从URL解析
let comps = URLComponents(url: url, resolvingAgainstBaseURL: false)
根据URL输出结构化字段,用于onOpenURL、处理回调URL等场景。
例如:
guard let comps = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return }
let host = comps.host
let items = comps.queryItems
resolvingAgainstBaseURL表示是否使用baseURL(基准URL)补全当前URL中缺失的部分,只有在处理相对URL时才有意义,对于https://、myapp:// 等绝对URL没有影响,默认为false。
let base = URL(string: "https://example.com/shop/")!
let url = URL(string: "detail?id=3", relativeTo: base)!
URLComponents(url: url, resolvingAgainstBaseURL: true)
// 返回
scheme = https
host = example.com
path = /shop/detail
query = id=3
2、手动构造
var comps = URLComponents()
comps.scheme = "myapp"
comps.host = "open"
comps.queryItems = [
URLQueryItem(name: "id", value: "123")
]
let url = comps.url
用于构造回调URL、自动编码、拼接参数等场景。
3、从字符串解析
let comps = URLComponents(string: urlString)
接收String类型,容易受编码影响,不常用。
解析字段
创建URLComponents:
let comps = URLComponents(url: url, resolvingAgainstBaseURL: false)
可以解析:
1、scheme:URL 的协议部分(如 http、https、ftp 等),例如ImageSlim。
2、user:用户名,例如root。
3、password:密码,例如password。
4、host:主机(通常是域名或 IP 地址)。
5、port:端口,例如80端口,若未设置,会使用协议的默认端口号。
6、path:路径,用于指定主机中的资源位置,例如 /temp。
7、queryItems:查询参数,一个 URLQueryItem 数组,表示查询参数。每个 URLQueryItem 包含一个键值对(name 和 value),用于构造 URL 的查询字符串,例如 id=123。
8、fragment:锚点,例如 #top。
使用示例
1、构建URLComponents 通过设置 URLComponents 的各个属性,最终生成了一个完整的 URL:
import Foundation
var components = URLComponents()
components.scheme = "https" // 设置协议
components.host = "www.example.com" // 设置主机
components.path = "/search" // 设置路径
components.queryItems = [
URLQueryItem(name: "q", value: "Swift URL"), // 添加查询参数
URLQueryItem(name: "lang", value: "en")
]
if let url = components.url { // 将 URLComponents 转化为 URL
print("URL: \(url)") // 输出完整的 URL
} else {
print("URL 创建失败")
}
上述代码会生成并输出一个完整的 URL:
URL: https://www.example.com/search?q=Swift%20URL&lang=en
2、解析 URL
URLComponents 解析现 URL,并提取其各个部分:
if let components = URLComponents(string: "https://www.example.com/search?q=Swift%20URL&lang=en") {
print("Scheme: \(components.scheme ?? "")") // 输出: https
print("Host: \(components.host ?? "")") // 输出: www.example.com
print("Path: \(components.path)") // 输出: /search
if let queryItems = components.queryItems {
for item in queryItems {
print("Query Item: \(item.name) = \(item.value ?? "")")
}
}
}
总结
URLComponents 提供了一个便捷的方式来构建和解析 URL,避免了 URL 字符串拼接中的错误和繁琐的编码处理。
