解析 URL 字符串以获取键值的最佳方法?

问题描述:

我需要解析这样的 URL 字符串:

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

我需要将 NSString 拆分为信号部分,例如 cid=241&avg_rating=4.82280613104.我一直在用 substringWithRange: 做这个,但是值以随机顺序返回,所以把它搞砸了.是否有任何允许轻松解析的类,您基本上可以将其转换为 NSDictionary 以便能够读取键的值(例如 ValueForKey:cid 应返回 241).或者有没有比使用 NSMakeRange 获取子字符串更简单的解析方法?

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?

edit(2018 年 6 月):这个答案更好.Apple 在 iOS 7 中添加了 NSURLComponents.

edit (June 2018): this answer is better. Apple added NSURLComponents in iOS 7.

我会创建一个字典,用

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

然后填充字典:

for (NSString *keyValuePair in urlComponents)
{
    NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
    NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
    NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];

    [queryStringDictionary setObject:value forKey:key];
}

然后您可以使用

[queryStringDictionary objectForKey:@"ad_eurl"];

这是未经测试的,您可能应该进行更多错误测试.

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