iOS8 이상의 경우 다음을 사용합니다 NSURLComponents
.
+(NSDictionary<NSString *, NSString *> *)queryParametersFromURL:(NSURL *)url {
NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
NSMutableDictionary<NSString *, NSString *> *queryParams = [NSMutableDictionary<NSString *, NSString *> new];
for (NSURLQueryItem *queryItem in [urlComponents queryItems]) {
if (queryItem.value == nil) {
continue;
}
[queryParams setObject:queryItem.value forKey:queryItem.name];
}
return queryParams;
}
아래 iOS 8의 경우 :
+(NSDictionary<NSString *, NSString *> *)queryParametersFromURL:(NSURL *)url
NSMutableDictionary<NSString *, NSString *> * parameters = [NSMutableDictionary<NSString *, NSString *> new];
[self enumerateKeyValuePairsFromQueryString:url.query completionblock:^(NSString *key, NSString *value) {
parameters[key] = value;
}];
return parameters.copy;
}
- (void)enumerateKeyValuePairsFromQueryString:(NSString *)queryString completionBlock:(void (^) (NSString *key, NSString *value))block {
if (queryString.length == 0) {
return;
}
NSArray *keyValuePairs = [queryString componentsSeparatedByString:@"&"];
for (NSString *pair in keyValuePairs) {
NSRange range = [pair rangeOfString:@"="];
NSString *key = nil;
NSString *value = nil;
if (range.location == NSNotFound) {
key = pair;
value = @"";
}
else {
key = [pair substringToIndex:range.location];
value = [pair substringFromIndex:(range.location + range.length)];
}
key = [self decodedStringFromString:key];
key = key ?: @"";
value = [self decodedStringFromString:value];
value = value ?: @"";
block(key, value);
}
}
+ (NSString *)decodedStringFromString:(NSString *)string {
NSString *input = shouldDecodePlusSymbols ? [string stringByReplacingOccurrencesOfString:@"+" withString:@" " options:NSLiteralSearch range:NSMakeRange(0, string.length)] : string;
return [input stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}