You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
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
}
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
The text was updated successfully, but these errors were encountered: