How to parse URL # fragments with query items in Swift

人走茶凉 提交于 2020-05-16 03:07:45

问题


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

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

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

into key values for:

  • access_token, expires_in, scope

回答1:


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


来源:https://stackoverflow.com/questions/57933247/how-to-parse-url-fragments-with-query-items-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!