Joris Kluivers

I like to build software.

NSURLComponents

Along with the new URL loading classes (NSURLSession & family) iOS 7 and Mavericks also bring a new way of constructing URLs. Similar to what NSDateComponents provides for a NSDate we can now use NSURLComponents to inspect, build and modify NSURLs.

An example:

NSURLComponents *components = [NSURLComponents new];
components.scheme = @"http";
components.host = @"joris.kluivers.nl";
components.path = @"/blog/2013/10/17/nsurlcomponents/";

NSURL *url = [components URL];
// url now equals:
// http://joris.kluivers.nl/blog/2013/10/17/nsurlcomponents/

A NSURL object is only returned if the combination of set properties on NSURLComponents result in a valid URL, nil will be returned otherwise.

Use initWithURL:resolveAgainstBaseURL: or initWithString: to create a components object with an initial set of values.

I would have linked above API to the official documentation, unfortunately like with many other recently introduced functionality nothing is available online yet. The only reference to NSURLComponents is it’s public definition in NSURL.h in the relevant SDKs. So I’ve published the relevant NSURLComponents declaration as a gist for easy online access.

Out of all the newly introduced API’s on both Mac and iOS this class will probably be the one I use most.

Feedback

Any feedback is welcome. I’m @kluivers on twitter.

For more posts about new iOS 7 & Mavericks additions see also: