Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 153 lines (121 sloc) 4.951 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
//
// KSURLQueryUtilities.m
// Sandvox
//
// Created by Mike on 27/07/2012.
// Copyright (c) 2012 Karelia Software. All rights reserved.
//

#import "KSURLQueryUtilities.h"


@implementation NSURL (KSURLQueryUtilities)

- (NSDictionary *)ks_queryParameters;
{
NSDictionary *result = [[self class] ks_parametersOfQuery:[self query]];
    return result;
}

- (NSURL *)ks_URLWithQueryParameters:(NSDictionary *)parameters;
{
NSString *query = [NSURL ks_queryWithParameters:parameters];
return [NSURL URLWithString:[@"?" stringByAppendingString:query] relativeToURL:self];
}

+ (NSURL *)ks_URLWithScheme:(NSString *)scheme
                       host:(NSString *)host
                       path:(NSString *)path
            queryParameters:(NSDictionary *)parameters;
{
    NSURL *baseURL = [[NSURL alloc] initWithScheme:scheme host:host path:path];
    NSURL *result = [baseURL ks_URLWithQueryParameters:parameters];
    [baseURL release];
    return result;
}

/* These 2 methods form the main backbone for URL query operations
*/

+ (NSString *)ks_queryWithParameters:(NSDictionary *)parameters;
{
// Build the list of parameters as a string
NSMutableString *parametersString = [NSMutableString string];

if (nil != parameters)
{
NSEnumerator *enumerator = [parameters keyEnumerator];
NSString *key;
BOOL thisIsTheFirstParameter = YES;

while (nil != (key = [enumerator nextObject]))
{
id rawParameter = [parameters objectForKey: key];
NSString *parameter = nil;

// Treat arrays specially, otherwise just get the object description
if ([rawParameter isKindOfClass:[NSArray class]]) {
parameter = [rawParameter componentsJoinedByString:@","];
}
else {
parameter = [rawParameter description];
}

// Append the parameter and its key to the full query string
if (!thisIsTheFirstParameter)
{
[parametersString appendString:@"&"];
}
else
{
thisIsTheFirstParameter = NO;
}
[parametersString appendFormat:
             @"%@=%@",
             [key ks_stringByAddingQueryComponentPercentEscapes],
             [parameter ks_stringByAddingQueryComponentPercentEscapes]];
}
}
return parametersString;
}

+ (NSDictionary *)ks_parametersOfQuery:(NSString *)queryString;
{
NSMutableDictionary *result = [NSMutableDictionary dictionary];
    
    // Handle & or ; as separators, as per W3C recommendation
    NSCharacterSet *seperatorChars = [NSCharacterSet characterSetWithCharactersInString:@"&;"];
NSArray *keyValues = [queryString componentsSeparatedByCharactersInSet:seperatorChars];
NSEnumerator *theEnum = [keyValues objectEnumerator];
NSString *keyValuePair;

while (nil != (keyValuePair = [theEnum nextObject]) )
{
NSRange whereEquals = [keyValuePair rangeOfString:@"="];
if (NSNotFound != whereEquals.location)
{
NSString *key = [keyValuePair substringToIndex:whereEquals.location];
NSString *value = [[keyValuePair substringFromIndex:whereEquals.location+1] ks_stringByReplacingQueryComponentPercentEscapes];
[result setValue:value forKey:key];
}
}
return result;
}

@end


@implementation NSString (KSURLQueryUtilities)

/*
By default, with null:
encoded: #%<>[\]^`{|}" space
Not encoded: !$&'()*+,-./:;=?@_~
exclamation!number%23dollar$percent%25ampersand&tick'lparen(rparen)aster*plus+space%20comma,dash-dot.slash/colon:semicolon;lessthan%3Cequals=greaterthan%3Equestion?at@lbracket%5Bbackslashl%0Dbracket%5Dcaret%5Eunderscore_backtick%60lbrace%7Bvbar%7Crbrace%7Dtilde~doublequote%22
RFC2396: Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.
Changed to NOT convert space into + ... while this is fine for web parameters, it doesn't work on mail clients reliably (e.g. mailto:foo@bar.com?subject=Hi+There+Mom)
*/

- (NSString *)ks_stringByAddingQueryComponentPercentEscapes;
{
    CFStringRef converted = CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                    (CFStringRef)self,
                                                                    NULL,
                                                                    CFSTR(";/?:@&=+,$%"),
                                                                    kCFStringEncodingUTF8);
    NSString *result = NSMakeCollectable(converted);
    return [result autorelease];
}

/*! Decode a URL's query-style string, taking out the + and %XX stuff
*/
- (NSString *)ks_stringByReplacingQueryComponentPercentEscapes
{
NSString *ish = [self stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableString *result = [ish mutableCopy];
    [result replaceOccurrencesOfString:@"+"
                            withString:@" "
                               options:NSLiteralSearch
                                 range:NSMakeRange(0, [result length])]; // fix + signs too!
    
return [result autorelease];
}

@end
Something went wrong with that request. Please try again.