NSURL with NSURLComponents and NSURLQueryItem in example
September 15, 2015

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
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 *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
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
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.