Skip to content

Instantly share code, notes, and snippets.

@amleszk
Created May 14, 2014 21:11
Show Gist options
  • Save amleszk/c79d0f6701022a91d8da to your computer and use it in GitHub Desktop.
Save amleszk/c79d0f6701022a91d8da to your computer and use it in GitHub Desktop.
Adding a query string to an NSURL
#import "NSURL+MUAdditions.h"
@implementation NSURL (MUAdditions)
-(NSURL*) URLByAppendingQueryString:(NSString*)queryString
{
NSString *absoluteString = [self absoluteString];
NSInteger startOfQueryString = [absoluteString rangeOfString:@"?"].location;
NSInteger startOfFragment = [absoluteString rangeOfString:@"#"].location;
NSString *absoluteStringWithAdditionalQueryString;
//fragment & query present
if (startOfFragment != NSNotFound && startOfQueryString != NSNotFound) {
NSRange rangeOfQueryString = NSMakeRange(startOfQueryString, startOfFragment-startOfQueryString);
absoluteStringWithAdditionalQueryString =
[self URLStringByReplacingQueryStringInURLString:absoluteString queryStringRange:rangeOfQueryString additionalQueryString:queryString];
}
//no fragment / with query
else if (startOfQueryString != NSNotFound) {
NSRange rangeOfQueryString = NSMakeRange(startOfQueryString, [absoluteString length]-startOfQueryString);
absoluteStringWithAdditionalQueryString =
[self URLStringByReplacingQueryStringInURLString:absoluteString queryStringRange:rangeOfQueryString additionalQueryString:queryString];
}
//fragment / no query
else if (startOfFragment != NSNotFound) {
NSRange rangeOfQueryString = NSMakeRange(startOfFragment, 0);
NSString *stringWithQuestionMark = [NSString stringWithFormat:@"?%@",queryString];
absoluteStringWithAdditionalQueryString = [absoluteString stringByReplacingCharactersInRange:rangeOfQueryString withString:stringWithQuestionMark];
} else {
absoluteStringWithAdditionalQueryString = [absoluteString stringByAppendingFormat:@"?%@",queryString];
}
NSURL *newURL = [NSURL URLWithString:absoluteStringWithAdditionalQueryString];
NSAssert(newURL, @"Expeced URL created non-nil, original: %@ new: %@",absoluteString,absoluteStringWithAdditionalQueryString);
return newURL;
}
-(NSString*) URLStringByReplacingQueryStringInURLString:(NSString*)absoluteURLString
queryStringRange:(NSRange)queryStringRange
additionalQueryString:(NSString*)additionalQueryString
{
NSString *stringWithAppendedParams = [NSString stringWithFormat:@"%@&%@",[absoluteURLString substringWithRange:queryStringRange],additionalQueryString];
NSString *absoluteStringWithAdditionalQueryString = [absoluteURLString stringByReplacingCharactersInRange:queryStringRange withString:stringWithAppendedParams];
return absoluteStringWithAdditionalQueryString;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment