有时候查询参数会以URL片段的形式而不是查询参数的形式传递 - 比如在OAuth流程中提供仅客户端访问的参数。
如何解析像这样的URL:
https://example.com/auth-callback#access_token=mytoken&expires_in=36000&scope=zap+profile
并将其转换为以下键值对:
- access_token、expires_in、scope
let url = URL(string: "https://example.com/auth-callback#access_token=mytoken&expires_in=36000&scope=zap+profile")
var components = URLComponents()
components.query = url.fragment
for item in components.queryItems! {
print("\(item.name): \(item.value)")
}