views:

41

answers:

1

I have an NSString with the value of

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

How can I get everything before the 3rd level?

http://digg.com/news/
+3  A: 

This isn't exactly the third level, mind you. 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 be username: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:[email protected]:8080/some/path/file.html?foo=bar#baz

As you can see, it can get quite lengthy and can bear lots of informations. 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.

NSURL has a wide range of accessors. You may check them in the documentation for the NSURL class, 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:0]];
zneak
thank you so much
Melina