提问人:Sarthak 提问时间:4/25/2022 最后编辑:Sarthak 更新时间:4/26/2022 访问量:685
如何解析 url 以获取键和值
How to parse a url to get key and value
问:
我引用这个答案来解析 url,但是当解析这个 url
NSString *urlString = @"https://www.example.com/product-detail?journey_id=123456&iswa=1";
我正在得到我的第一把钥匙,但我只需要作为我的钥匙。https://www.example.com/product-detail?journey_id
journey_id
这是我在编码中所做的:
NSString *urlString = @"https://www.example.com/product-detail?journey_id=123456&iswa=1";
NSMutableDictionary *waLoginDictionary = [[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];
[waLoginDictionary setObject:value forKey:key];
}
NSLog(@"%@", waLoginDictionary);
我得到这个输出:
{
"https://www.example.com/product-detail?journey_id" = 123456;
iswa = 1;
}
答:
3赞
Prasad Parab
4/25/2022
#1
你所指的答案已经过时了,作者本人已经进行了相应的更新。Apple 在对象中添加了。[URLQueryItem]
URLComponent
试试这个。
迅速
let urlString = "https://www.example.com/product-detail?journey_id=123456&iswa=1"
var dict: [String : String] = [:]
if let urlComponents = URLComponents(string: urlString), let queryItems = urlComponents.queryItems {
for item in queryItems {
dict[item.name] = item.value
}
}
print("dict : \(dict)")
目标 - C
NSString *urlString = @"https://www.example.com/product-detail?journey_id=123456&iswa=1";
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSURLComponents *urlComponents = [NSURLComponents componentsWithString:urlString];
NSArray *queryItems = [urlComponents queryItems];
for (NSURLQueryItem *item in queryItems) {
[dict setValue:item.value forKey:item.name];
}
NSLog(@"dict %@", dict);
评论
0赞
Sarthak
4/25/2022
是的,这个解决方案正是我想要的.如果我们能检查一下,那将是非常有用的,如果我的 url 包含,那么我们只需要在字典中添加参数?而且我们不需要在 dict 中添加 iswa 参数。iswa == 1
0赞
Prasad Parab
4/25/2022
是的,您可以在循环访问查询项时根据需要在字典中检查和添加参数。
0赞
Sarthak
4/26/2022
这里我在ViewDidload方法下面复制了这个解决方案,但它向我显示错误:“使用未声明的标识符'NSURLDownload'”。
评论
NSURLComponents