Create a gist now

Instantly share code, notes, and snippets.

Retrieve specific query string parameter from NSURL
func getQueryStringParameter(url: String, param: String) -> String? {
let url = NSURLComponents(string: url)!
return
(url.queryItems? as [NSURLQueryItem])
.filter({ (item) in item.name == param }).first?
.value()
}
@ryanio
ryanio commented Jun 18, 2015

This is great, thanks!

@BlakeBarrett

Thanks for posting that!
I really like your approach. Here's my riff on it:

func getQueryStringParameter(url: String?, param: String) -> String? {
    if let url = url, urlComponents = NSURLComponents(string: url), queryItems = (urlComponents.queryItems as? [NSURLQueryItem]) {
        return queryItems.filter({ (item) in item.name == param }).first?.value!
    }
    return nil
}
@corydolphin

This is great, but it is absolutely absurd that it is so difficult to achieve such a simple and common task.

@Digiraf
Digiraf commented Sep 10, 2015

Thanks!

@InsertNetan

Thanks !!
if this is interesting i wrote a similar extension to achieve the same thing.

https://gist.github.com/InsertNetan/372c9f51549ea96e5af2

@hemang-azilen

Is it available for Objective-C?

@hstntn
hstntn commented Jan 5, 2017

This is great, thanks! 💯

@hijohnnylin

Thanks. For Swift 3:

func getQueryStringParameter(url: String?, param: String) -> String? {
    if let url = url, let urlComponents = URLComponents(string: url), let queryItems = (urlComponents.queryItems) {
        return queryItems.filter({ (item) in item.name == param }).first?.value!
    }
    return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment