Instantly share code, notes, and snippets.

Embed
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

This comment has been minimized.

Show comment
Hide comment
@ryanio

ryanio Jun 18, 2015

This is great, thanks!

ryanio commented Jun 18, 2015

This is great, thanks!

@BlakeBarrett

This comment has been minimized.

Show comment
Hide comment
@BlakeBarrett

BlakeBarrett Jul 1, 2015

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
}

BlakeBarrett commented Jul 1, 2015

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 comment has been minimized.

Show comment
Hide comment
@corydolphin

corydolphin Jul 18, 2015

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

corydolphin commented Jul 18, 2015

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

@Digiraf

This comment has been minimized.

Show comment
Hide comment
@Digiraf

Digiraf commented Sep 10, 2015

Thanks!

@InsertNetan

This comment has been minimized.

Show comment
Hide comment
@InsertNetan

InsertNetan Jan 25, 2016

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

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

InsertNetan commented Jan 25, 2016

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

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

@hemang-azilen

This comment has been minimized.

Show comment
Hide comment
@hemang-azilen

hemang-azilen Feb 13, 2016

Is it available for Objective-C?

hemang-azilen commented Feb 13, 2016

Is it available for Objective-C?

@hstntn

This comment has been minimized.

Show comment
Hide comment
@hstntn

hstntn Jan 5, 2017

This is great, thanks! 💯

hstntn commented Jan 5, 2017

This is great, thanks! 💯

@hijohnnylin

This comment has been minimized.

Show comment
Hide comment
@hijohnnylin

hijohnnylin Jan 16, 2017

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
}

hijohnnylin commented Jan 16, 2017

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
}
@ArthurXHK

This comment has been minimized.

Show comment
Hide comment
@ArthurXHK

ArthurXHK May 29, 2017

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
}

ArthurXHK commented May 29, 2017

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

This comment has been minimized.

Show comment
Hide comment
@ldrr

ldrr 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
    }
}

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
    }
}
@cerniuk

This comment has been minimized.

Show comment
Hide comment
@cerniuk

cerniuk Feb 18, 2018

This is suppose to be easier than Objective C?

cerniuk commented Feb 18, 2018

This is suppose to be easier than Objective C?

@TizianoCoroneo

This comment has been minimized.

Show comment
Hide comment
@TizianoCoroneo

TizianoCoroneo Apr 24, 2018

why guard?

extension URL {
    func getQueryString(parameter: String) -> String? {
        return URLComponents(url: self, resolvingAgainstBaseURL: false)?
            .queryItems?
            .first { $0.name == parameter }?
            .value
    }
}

TizianoCoroneo commented Apr 24, 2018

why guard?

extension URL {
    func getQueryString(parameter: String) -> String? {
        return URLComponents(url: self, resolvingAgainstBaseURL: false)?
            .queryItems?
            .first { $0.name == parameter }?
            .value
    }
}
@dimitardanailov

This comment has been minimized.

Show comment
Hide comment
@dimitardanailov

dimitardanailov Jul 11, 2018

I'm using Objective - C and Categories

Header file

#import <Foundation/Foundation.h>

@interface NSString (getQueryStringParameter)

/**
 * @method getQueryStringParameter:url:key
 * @abstract Method get specific value from NSURL
 *
 * I wrote this method follow these guides:
 * - https://gist.github.com/gillesdemey/509bb8a1a8c576ea215a
 * - https://stackoverflow.com/questions/8756683/best-way-to-parse-url-string-to-get-values-for-keys/26406426#26406426
 *
 */
+ (NSString *)getQueryStringParameter:(NSURL *)url :(NSString *)key;

@end

Implementation

#import <Foundation/Foundation.h>

#import "NSString+getQueryStringParameter.h"

@implementation NSString (Validation)

+ (NSString *)getQueryStringParameter:(NSURL *)url :(NSString *)key {
    NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url
                                                resolvingAgainstBaseURL:NO];
    NSArray *queryItems = urlComponents.queryItems;
    
    if ([queryItems count] == 0) return @"";
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", key];
    NSURLQueryItem *queryItem = [[queryItems
                                  filteredArrayUsingPredicate:predicate]
                                 firstObject];
    
    return queryItem.value;
}

dimitardanailov commented Jul 11, 2018

I'm using Objective - C and Categories

Header file

#import <Foundation/Foundation.h>

@interface NSString (getQueryStringParameter)

/**
 * @method getQueryStringParameter:url:key
 * @abstract Method get specific value from NSURL
 *
 * I wrote this method follow these guides:
 * - https://gist.github.com/gillesdemey/509bb8a1a8c576ea215a
 * - https://stackoverflow.com/questions/8756683/best-way-to-parse-url-string-to-get-values-for-keys/26406426#26406426
 *
 */
+ (NSString *)getQueryStringParameter:(NSURL *)url :(NSString *)key;

@end

Implementation

#import <Foundation/Foundation.h>

#import "NSString+getQueryStringParameter.h"

@implementation NSString (Validation)

+ (NSString *)getQueryStringParameter:(NSURL *)url :(NSString *)key {
    NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url
                                                resolvingAgainstBaseURL:NO];
    NSArray *queryItems = urlComponents.queryItems;
    
    if ([queryItems count] == 0) return @"";
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", key];
    NSURLQueryItem *queryItem = [[queryItems
                                  filteredArrayUsingPredicate:predicate]
                                 firstObject];
    
    return queryItem.value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment