Best way to parse URL string to get values for keys

Best way to parse URL string to get values for keys

I need to parse a URL string like this one:

&ad_eurl=http://www.youtube.com/video/4bL4FI1Gz6s&hl=it_IT&iv_logging_level=3&ad_flags=0&endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vfl6o3XZn.swf&cid=241&cust_gender=1&avg_rating=4.82280613104
I need to split the NSString up into the signle parts like cid=241 and &avg_rating=4.82280613104. I've been doing this with substringWithRange: but the values return in a random order, so that messes it up. Is there any class that allows easy parsing where you can basically convert it to NSDictionary to be able to read the value for a key (for example ValueForKey:cid should return 241). Or is there just another easier way to parse it than using NSMakeRange to get a substring?

I would create a dictionary, get an array of the key/value pairs with

NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];
NSArray *urlComponents = [urlString componentsSeparatedByString:@"&"];


Then populate the dictionary :

for (NSString *keyValuePair in urlComponents)
{
    NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
    NSString *key = [pairComponents objectAtIndex:0];
    NSString *value = [pairComponents objectAtIndex:1];

    [queryStringDictionary setObject:value forKey:key];
}


You can then query with
[queryStringDictionary objectForKey:@"ad_eurl"];


This is untested, and you should probably do some more error tests.

猜你喜欢

转载自zl4393753.iteye.com/blog/1752681
今日推荐