问题
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