Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to parse URL string to get values for keys?

I need to parse a URL string like this one:

&ad_eurl=http://www.youtube.com/video/4bL4FI1Gz6s&hl=it_IT&iv_logging_level=3&ad_flags=0&endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vfl6o3XZn.swf&cid=241&cust_gender=1&avg_rating=4.82280613104 

I need to split the NSString up into the signle parts like cid=241 and &avg_rating=4.82280613104. I've been doing this with substringWithRange: but the values return in a random order, so that messes it up. Is there any class that allows easy parsing where you can basically convert it to NSDictionary to be able to read the value for a key (for example ValueForKey:cid should return 241). Or is there just another easier way to parse it than using NSMakeRange to get a substring?

like image 550
JonasG Avatar asked Jan 06 '12 10:01

JonasG


People also ask

How can I get parameters from a URL string?

The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.

What is URL parsing?

URL Parsing. The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.

What is URL query string?

A query string is the portion of a URL where data is passed to a web application and/or back-end database. The reason we need query strings is that the HTTP protocol is stateless by design. For a website to be anything more than a brochure, you need to maintain state (store data).


2 Answers

edit (June 2018): this answer is better. Apple added NSURLComponents in iOS 7.

I would create a dictionary, get an array of the key/value pairs with

NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init]; NSArray *urlComponents = [urlString componentsSeparatedByString:@"&"]; 

Then populate the dictionary :

for (NSString *keyValuePair in urlComponents) {     NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];     NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];     NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];      [queryStringDictionary setObject:value forKey:key]; } 

You can then query with

[queryStringDictionary objectForKey:@"ad_eurl"]; 

This is untested, and you should probably do some more error tests.

like image 27
Thomas Joulin Avatar answered Oct 13 '22 05:10

Thomas Joulin


I also answered this at https://stackoverflow.com/a/26406478/215748.

You can use queryItems in URLComponents.

When you get this property’s value, the NSURLComponents class parses the query string and returns an array of NSURLQueryItem objects, each of which represents a single key-value pair, in the order in which they appear in the original query string.

let url = "http://example.com?param1=value1&param2=param2" let queryItems = URLComponents(string: url)?.queryItems let param1 = queryItems?.filter({$0.name == "param1"}).first print(param1?.value) 

Alternatively, you can add an extension on URL to make things easier.

extension URL {     var queryParameters: QueryParameters { return QueryParameters(url: self) } }  class QueryParameters {     let queryItems: [URLQueryItem]     init(url: URL?) {         queryItems = URLComponents(string: url?.absoluteString ?? "")?.queryItems ?? []         print(queryItems)     }     subscript(name: String) -> String? {         return queryItems.first(where: { $0.name == name })?.value     } } 

You can then access the parameter by its name.

let url = URL(string: "http://example.com?param1=value1&param2=param2")! print(url.queryParameters["param1"]) 
like image 198
Onato Avatar answered Oct 13 '22 05:10

Onato