Objective C 解析 url 字符串的请求参数为 NSDictionary 字典类
以下使用 Objective C,将 url 的NSString
格式的请求参数部分,转换为字典NSDictionary
对象,方便对参数进行访问。
代码实现
提取 url 中需要处理的字符串:从问号 ? 开始,到锚部分(从 # 号开始的部分)。字符串以 & 符号分开成键值对,开始拼接存入键类。以下方法通用适应于 IOS 项目。
// 解析 url 字符串为 dictionary
- (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;
}
调用示例
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);
运行的结果:
params1: {
}
params2: {
a = 1;
b = 2;
}
params3: {
c = 3;
d = 4;
}