Question

Any ideas how I can get the root of a website from an NSString or an NSURL? So if my URL was http://www.foo.com/bar/baragain how would I get http://www.foo.com/?

Was it helpful?

Solution

By using [url scheme] and [url host] like so:

NSURL *url = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"];
NSLog(@"Base url: %@://%@", [url scheme], [url host]);
// output is http://www.foo.com

OTHER TIPS

NSURL *url = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"];
NSURL *root = [NSURL URLWithString:@"/" relativeToURL:url];
NSLog(@"root = '%@'", root.absoluteString); // root = 'http://www.foo.com/'

You can remove the NSURL's path from the string. This accounts for port numbers and other data that are part of the root site.

NSString *urlString = @"http://www.foo.com/bar/baragain";
NSURL *rootUrl = [NSURL URLWithString:urlString];
NSString *rootUrlString = [urlString stringByReplacingOccurrencesOfString:rootUrl.path withString:@""];
NSString *str = @"http://www.foo.com/bar/baragain"; 
NSArray *temp = [str componentsSeparatedByString: @".com"];
str = [NSString stringWithFormat: @"%@%@", [temp objectAtIndex:0], @".com"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top