如何解析 url 以获取键和值

How to parse a url to get key and value

我指的是 this 解析 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;
} 

您所指的答案已过时,作者本人已相应更新。 Apple 在 URLComponent 对象中添加了 [URLQueryItem]

试试这个。

Swift

    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)")

Objective - 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);