Last active
          March 24, 2021 10:53 
        
      - 
      
- 
        Save gillesdemey/509bb8a1a8c576ea215a to your computer and use it in GitHub Desktop. 
    Retrieve specific query string parameter from NSURL
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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() | |
| } | 
why guard?
extension URL {
    func getQueryString(parameter: String) -> String? {
        return URLComponents(url: self, resolvingAgainstBaseURL: false)?
            .queryItems?
            .first { $0.name == parameter }?
            .value
    }
}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
  
            
This is suppose to be easier than Objective C?