Table of contents

Parsing the URL query string into an NSDictionary using Objective C

Objective C Mar 03, 2020 Viewed 836 Comments 0

In IOS, we want to parsing the URL query string into NSDictionary. It is convenient for us to read.

Example

Extract the query string from the url. It starts with ?char and ends with the anchor, the part that starts with #. The Query string are separated into key-value pairs by &.

- (NSMutableDictionary *)parseUrlQuery2Diction:(NSString *)url {
    NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];
    NSRange range = [url rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return queryStringDictionary;
    }
    url = [url substringFromIndex:(range.location + 1)];
    range = [url rangeOfString:@"#"];
    if (range.location != NSNotFound) {
        url = [url substringToIndex:(range.location)];
    }
    NSArray *urlComponents = [url componentsSeparatedByString:@"&"];
    for (NSString *keyValuePair in urlComponents)
    {
        NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
        NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
        NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];
        if ([key length] == 0) {
            continue;
        }
        [queryStringDictionary setObject:value forKey:key];
    }
    return queryStringDictionary;
}

Use it

NSString *url1 = @"https://localhost:8080/test";
NSDictionary * params1 = [self parseUrlQuery2Diction:url1];
NSLog(@"params1: %@", params1);
NSString *url2 = @"https://localhost:8080/test?a=1&b=2";
NSDictionary * params2 = [self parseUrlQuery2Diction:url2];
NSLog(@"params2: %@", params2);
NSString *url3 = @"https://localhost:8080/test?c=3&d=4#xyz";
NSDictionary * params3 = [self parseUrlQuery2Diction:url3];
NSLog(@"params3: %@", params3);

Run and get the following result.

params1: {
}
params2: {
    a = 1;
    b = 2;
}
params3: {
    c = 3;
    d = 4;
}
Updated Mar 03, 2020