Last active
August 30, 2022 07:29
-
-
Save alongotv/29612dd49d9e22a1a61074b589a4b00a to your computer and use it in GitHub Desktop.
Removes obsolete parameters from URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Usage: | |
let urlString = "https://example.com/?foo=bar¶m2=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