如何使用Swift解析带有查询参数的URL片段

3

有时候查询参数会以URL片段的形式而不是查询参数的形式传递 - 比如在OAuth流程中提供仅客户端访问的参数。

如何解析像这样的URL:

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

并将其转换为以下键值对:

  • access_token、expires_in、scope
1个回答

14
将片段属性作为查询字符串传递给新的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)")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接