get parts of NSURL

For example, if we have

and would like to get

An URL is split like that way:

  • the protocol or scheme (here, http)
  • the :// delimiter
  • the username and the password (here there isn’t any, but it could beusername:password@hostname)
  • the host name (here,
  • the port (that would be :80 after the domain name for instance)
  • the path (here, /news/business/24hr)
  • the query string (that would be if you had GET parameters like ?foo=bar&baz=frob)
  • the fragment (that would be if you had an anchor in the link, like #foobar).

A “fully-featured” URL would look like this:

As you can see, it can get quite long and can contain a lot of information. Depending on the origin of your URL, you might want to do more or less elaborate concatenations. Though, for your example URL, what you seem to want is the protocol, the host and the first path component. (The element at index 0 in the array returned by -[NSString pathComponents] is simply “/”, so you’ll want the element at index 1. The other slashes are discarded.)

NSURL has a wide range of accessors. You may check them in the documentation for the NSURLclass, section Accessing the Parts of the URL. You can see their effect on this page (scroll down a little). What you’ll want, though, is something like that:

NSURL* url = [NSURL URLWithString:@""];
NSString* reducedUrl = [NSString stringWithFormat:
    [url.pathComponents objectAtIndex:1]];

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s