NSURL with NSURLComponents and NSURLQueryItem in example

September 15, 2015

NSURL with NSURLComponents and NSURLQueryItem in example

NSURLComponents has been with us since iOS7, so I am not going to get through it, I will leave it to you, my lovely reader. In this article I am going to show you most practical use of NSURLComponents in combination with NSURLQueryItems objects, which happened to appear in iOS8. The best way to show its use, is through example of creation of GET request.

Creating base URL for request

First of all we need to create the base URL for our request. To do so, we need to provide either a NSString object to the initializer, or NSURL object:

NSString *stringURL = @"http://arsenkin.com";
NSURLComponents *components = [NSURLComponents componentsWithString:stringURL];
/* or */
NSURLComponents *components = [[NSURLComponents alloc] initWithString:stringURL];

This way we are creating our base URL, to whom we are going to add some parameters.

Creating query items

Now we need some queries. Lets say that we need to provide type of data we would like to get, for instance document_type parameter with value pdf and another parameter compression with value none:

NSURLQueryItem *documentType = [NSURLQueryItem queryItemWithName:@"document_type" value:@"pdf"];
NSURLQueryItem *compressionValue = [NSURLQueryItem queryItemWithName:@"compression" value:@"none"];

Pretty simple yet so convenient. Just imagine how fast you could create ten parameters with their values right from the NSDictionary, that you have created, for example, from the previous server's JSON response. Now the last part - combining it all together.

Creating final NSURL object

Final step - providing our query items to the NSURLComponents object and creation of our final URL:

components.queryItems = @[documentType, compressionValue];
NSURL *requestURL = components.URL; /* http://arsenkin.com?document_type=pdf&compression=none */

And that is all you need to do. With these two classes it is now very simple to create long request URLs with many parameters.

Comments

comments powered by Disqus