Search code examples
iosswiftobjective-cparsingcocoa-touch

How to parse a url to get key and value


I am refering this answer to parse url but when parse this url

NSString *urlString = @"https://www.example.com/product-detail?journey_id=123456&iswa=1";

I am getting my 1st key is https://www.example.com/product-detail?journey_id But I need only journey_id as my key.

This is what I have done in coding:

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

I am getting This output:

{
"https://www.example.com/product-detail?journey_id" = 123456;
iswa = 1;
} 

Solution

  • The answer you are referring to is outdated and has been updated accordingly by the writer himself. Apple added [URLQueryItem] in the URLComponent object.

    Try this.

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