Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How parse url to get 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading