如何在 Swift 中使用查询项解析 URL # 片段

mir*_*fer 2 url parsing oauth swift

查询参数有时会作为 URL 片段而不是查询参数传递 - 例如,在 OAuth 流期间提供仅客户端对参数的访问。

解析 URL 的最简单方法是什么:

  • https://example.com/auth-callback#access_token=mytoken&expires_in=36000&scope=zap+profile

成关键值:

  • access_token、expires_in、范围

mir*_*fer 8

只需将片段属性作为查询字符串传递给新的 URLComponent 并读取解析的查询对象:

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)")
}
Run Code Online (Sandbox Code Playgroud)