Consider the following URL:
http://www.example.com/?utm_source=adsite&utm_campaign=adcampaign&utm_term=adkeyword
We are interested in the query parameter value of utm_term. We can parse the URL using the following code:
This file contains 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
// https://hashaam.com/2017/09/02/get-specific-urlqueryitem-from-urlcomponents | |
func queryParam(urlString: String?, param: String) -> String? { | |
guard let urlString = urlString else { return nil } | |
guard let urlComponents = URLComponents(string: urlString) else { return nil } | |
guard let queryItems = urlComponents.queryItems else { return nil } | |
return queryItems.filter { queryItem in | |
return queryItem.name == param | |
}.first?.value | |
} |
And call the function using:
This file contains 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
// https://hashaam.com/2017/09/02/get-specific-urlqueryitem-from-urlcomponents | |
if let utmTermValue = queryParam(urlString: "http://www.example.com/?utm_source=adsite&utm_campaign=adcampaign&utm_term=adkeyword", param: "utm_term") { | |
// handle utmTermValue | |
} |