Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple key in URL, associated array in URL #34

Closed
cejanen opened this issue Mar 8, 2023 · 0 comments · Fixed by #38
Closed

Multiple key in URL, associated array in URL #34

cejanen opened this issue Mar 8, 2023 · 0 comments · Fixed by #38

Comments

@cejanen
Copy link
Collaborator

cejanen commented Mar 8, 2023

we need to map sometimes url parameter which value is array in syntax below

An URL extension to append query items, similar to Bhuvan Bhatt idea, but with a different signature:

it can detect failures (by returning nil instead of self), thus allowing custom handling of cases where the URL is not RFC 3986 compliant for instance.
it allows nil values, by actually passing any query items as parameters.
for performance, it allows passing multiple query items at a time.
extension URL {
/// Returns a new URL by adding the query items, or nil if the URL doesn't support it.
/// URL must conform to RFC 3986.
func appending(_ queryItems: [URLQueryItem]) -> URL? {
guard var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true) else {
// URL is not conforming to RFC 3986 (maybe it is only conforming to RFC 1808, RFC 1738, and RFC 2732)
return nil
}
// append the query items to the existing ones
urlComponents.queryItems = (urlComponents.queryItems ?? []) + queryItems

    // return the url from new url components
    return urlComponents.url
}

}
Usage

let url = URL(string: "https://example.com/...")!
let queryItems = [URLQueryItem(name: "id", value: nil),
URLQueryItem(name: "id", value: "22"),
URLQueryItem(name: "id", value: "33")]
let newUrl = url.appending(queryItems)!
print(newUrl)
Output:

https://example.com/...?id&id=22&id=33

@gajddo00 gajddo00 linked a pull request May 8, 2023 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants