Skip to content

Removing URL query parameters in Swift

Published: at 06:33 AM

Lots of app these days including their query parameter in their URL. This is useful to track the source of visitor of your app/website. Moreover, by incorporating query parameters in the URL, developers can gain insights into user behavior and preferences. This data can be invaluable for optimizing the user experience and tailoring content or features to meet the needs and interests of the audience. For instance, if a significant number of users are coming from a particular campaign or referral source, the app or website can adjust its marketing strategies or content offerings to better serve and engage those users.

However this can be source of frustration if you use URL as input of your app. You can incorrectly parse the URL since it contains query parameters. To remove this query parameter, you can use URLComponents then set the queryItems and fragment properties to nil.

Here’s how:

let urlString = "https://www.reddit.com/r/funnyvideos/comments/1cd5e84/i_cant_swim_either/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button"

let urlComponents = URLComponents(string: urlString)
urlComponents?.queryItems = nil
urlComponents?.fragment = nil

// result: URL(string: https://www.reddit.com/r/funnyvideos/comments/1cd5e84/i_cant_swim_either/)

You can also create an extension on String if you want

extension String {
    func cleaned() -> Self {
        var components = URLComponents(string: self)
        components?.queryItems = nil
        components?.fragment = nil
        return components?.string ?? self
    }
}

Then you can use it directly inside URL initializer

let cleanedURL2 = URL(string: urlString.cleaned())
print(cleanedURL2)

// result: URL(string: https://www.reddit.com/r/funnyvideos/comments/1cd5e84/i_cant_swim_either/)