get parts of NSURL

For example, if we have

http://digg.com/news/business/24hr

and would like to get

http://digg.com/news/

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, digg.com)
  • 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:

http://foobar:nicate@example.com:8080/some/path/file.html?foo=bar#baz

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:@"http://digg.com/news/business/24hr"];
NSString* reducedUrl = [NSString stringWithFormat:
    @"%@://%@/%@",
    url.scheme,
    url.host,
    [url.pathComponents objectAtIndex:1]];
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s