NSURL and NSURLComponents

NSURL and NSURLComponents are classes for handling URLs (Uniform Resource Locator). In this post we discuss the most important features of these classes.

Initialisation of a NSURL object

The initialisation of a NSURL object is very straight forward. The most common way is by specifying a string:

Just can also specify an URL that is relative to another URL:

Be careful! If you initialise a NSURL object with a string that is not a correct URL, the object becomes nil:

Accessing a NSURL object

First, you can access the url as a string:

But it is also possible to access just certain parts of the URL:

Comparing NSURLs

For comparing NSURL objects, you can use the  isEqual method:

Percent Encoding

If you are constructing an URL, you have to consider the percent encoding. Generally speaking, there are certain characters that are reserved characters (for example “#”) and are not allowed to be in certain parts of the url. For example, if you want to specify the character ‘#’ within a parameter, it must be encoded by ‘%23’. There is a function for strings, that does the job for you. In this example,  a query string gets encoded:

There are further NSCharacterSets you can apply to other parts of the URL:

  • URLFragmentAllowedCharacterSet
  • URLHostAllowedCharacterSet
  • URLPasswordAllowedCharacterSet
  • URLPathAllowedCharacterSet
  • URLQueryAllowedCharacterSet

You must be very careful in terms of handling the percent encoding. It is very easy to make mistakes here. So always double check where you are encoding your URLs correctly or not.

NSURLComponents

NSURLComponents is like a mutable NSURL and is available since iOS 7. It is in many regards much safer to use. You can for example construct a NSURLComponents object just like a NSURL with a string. Then, you can add a query string:

Because you specify certain parts of the URL, NSURLComponents is able to handle a lot of the percent encoding on its own. If you know that your string is already percent encoded, you have to use another property of NSURLComponents:

There are also corresponding properties for other parts of an URL as well.

Conclusion

NSURL and NSURLCompents  are the correct and easy way to handle URLs in iOS development. However, be careful in handling the percent encoding!

References

Image: @ Constantin Stanciu / shutterstock.com
NSURL Class Reference
NSURLComponents Class Reference

Book Tip

Big Nerd Range Guide: iOS Programming: Excellent introduction to iOS development. Some programming experience is recommended.

Amazon