Skip to content

Instantly share code, notes, and snippets.

@alongotv
Last active August 30, 2022 07:29
Show Gist options
  • Save alongotv/29612dd49d9e22a1a61074b589a4b00a to your computer and use it in GitHub Desktop.
Save alongotv/29612dd49d9e22a1a61074b589a4b00a to your computer and use it in GitHub Desktop.
Removes obsolete parameters from URL
/*
Usage:
let urlString = "https://example.com/?foo=bar&param2=none&__is_cowboy=false"
let url = URL(string: urlString)
let urlWithoutParameters = url?.removeParameters(with: ["param2", "__is_cowboy"])
print(urlWithoutParameters!)
Result: https://example.com/?foo=bar is printed
*/
// MARK: - Extensions to work with URL objects
extension URL {
/// Removes specified parameters from URL address
///
/// - Parameter keys: array of String, contains keys of parameters to delete
/// - Returns: URL object without specified params
func removeParameters(with keys: [String])-> URL {
let query = self.query
let arr = query?.components(separatedBy: "&")
var dict = Dictionary(uniqueKeysWithValues: arr!.map {
($0.split(separator: "=")[0], $0.split(separator: "=")[1]) })
var linkParams = ""
for key in keys {
dict.removeValue(forKey: Substring(key))
}
for element in dict {
linkParams += element.key + "=" + element.value + "&"
}
let finalStringUrl = self.absoluteString.components(separatedBy: "?")[0] + "?" + linkParams.dropLast()
return URL(string: finalStringUrl)!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment