如何在Swift中使用查询项解析URL#片段 [英] How to parse URL # fragments with query items in Swift

查看:398
本文介绍了如何在Swift中使用查询项解析URL#片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Query parameters sometimes get passed as URL fragments instead of query parameters - e.g. during OAuth flows to provide client-only access to parameters.

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

What's the simplest way to parse a URL like:

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

输入键值:

  • access_token,expires_in,范围

推荐答案

将片段属性作为查询字符串简单地传递到新的URLComponent并读取已解析的查询对象:

Simply pass the fragment property as a query string to a new URLComponent and read the parsed query objects:

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)")
}

这篇关于如何在Swift中使用查询项解析URL#片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆