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/
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/
This isn't exactly the third level, mind you. An URL is split like that way:
http):// delimiterusername:password@hostname)digg.com):80 after the domain name for instance)/news/business/24hr)?foo=bar&baz=frob)#foobar).A "fully-featured" URL would look like this:
http://foobar:nicate@example.com:8080/some/path/file.html;params-here?foo=bar#baz
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. For quick reference:
-[NSURL scheme] = http-[NSURL resourceSpecifier] = (everything from // to the end of the URL)-[NSURL user] = foobar-[NSURL password] = nicate-[NSURL host] = example.com-[NSURL port] = 8080-[NSURL path] = /some/path/file.html-[NSURL pathComponents] = @["/", "some", "path", "file.html"] (note that the initial / is part of it)-[NSURL lastPathComponent] = file.html-[NSURL pathExtension] = html-[NSURL parameterString] = params-here-[NSURL query] = foo=bar-[NSURL fragment] = bazWhat 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[1]];
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.)
 
    
     Playground provides an interactive way of seeing this in action. I hope you can enjoy doing the same, a fun way to learn NSURL an important topic in iOS.
Playground provides an interactive way of seeing this in action. I hope you can enjoy doing the same, a fun way to learn NSURL an important topic in iOS.
