Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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 commented Jun 18, 2015

This is great, thanks!

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
}

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

Digiraf commented Sep 10, 2015

Thanks!

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

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

Is it available for Objective-C?

hstntn commented Jan 5, 2017

This is great, thanks! 💯

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
}

will be better to do it with the function first(where predicate: (Element) throws -> Bool) rethrows -> Element? in Array.

func getQueryStringParameter(url: String?, param: String) -> String? {
    if let urlStr = url, let urlComponents = URLComponents(string: urlStr)?.queryItems {
        return queryItems.first(where: { $0.name == param })?.value
    }
    return nil
}

ldrr commented Dec 13, 2017

And having this as an extension of URL would look like this

extension URL {
    func getQueryStringParameter(param: String) -> String? {
        guard let urlComponents = NSURLComponents(url: self, resolvingAgainstBaseURL: false),
            let queryItems = urlComponents.queryItems else {
            return nil
        }

        return queryItems.first(where: { $0.name == param })?.value
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment