Last active
August 29, 2015 13:58
-
-
Save virasio/10253030 to your computer and use it in GitHub Desktop.
NSURL+Dictionaries — Returns properties query and fragment of NSURL as NSDictionary
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
@interface NSURL (Dictionaries) | |
@property (nonatomic, readonly) NSDictionary *queryDictionary; | |
@property (nonatomic, readonly) NSDictionary *fragmentDictionary; | |
- (NSURL *)URLByAppendingQueryParameters:(NSDictionary *)parameters; | |
@end |
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
#import "NSURL+Dictionaries.h" | |
@implementation NSURL (Dictionaries) | |
- (NSDictionary *)parseParametersString:(NSString *)parametersString { | |
NSMutableDictionary *dict = [NSMutableDictionary dictionary]; | |
NSArray *parameters = [parametersString componentsSeparatedByString:@"&"]; | |
for (NSString *parameter in parameters) { | |
NSArray *parts = [parameter componentsSeparatedByString:@"="]; | |
NSString *key = [[parts objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
if ([parts count] > 1) | |
{ | |
id value = [[parts objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
[dict setObject:value forKey:key]; | |
} | |
} | |
return [NSDictionary dictionaryWithDictionary:dict]; | |
} | |
- (NSDictionary *)queryDictionary { | |
return [self parseParametersString:self.query]; | |
} | |
- (NSDictionary *)fragmentDictionary { | |
return [self parseParametersString:self.fragment]; | |
} | |
- (NSURL *)URLByAppendingQueryParameters:(NSDictionary *)parameters { | |
if (!parameters || parameters.count == 0) { | |
return [self copy]; | |
} | |
NSMutableString *queryString = [NSMutableString stringWithString:@""]; | |
for (NSString *key in parameters) { | |
[queryString appendString:[NSString stringWithFormat:@"%@%@=%@", | |
([queryString isEmpty] ? @"" : @"&"), key, parameters[key]]]; | |
} | |
NSString *URLString = [[NSString alloc] initWithFormat:@"%@%@%@", [self absoluteString], | |
[self query] ? @"&" : @"?", queryString]; | |
return [NSURL URLWithString:URLString]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment