trx25
trx25

Reputation: 359

Get root of website from NSString or NSUrl

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/?

Upvotes: 7

Views: 5629

Answers (4)

Jeffrey Sun
Jeffrey Sun

Reputation: 8049

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:@""];

Upvotes: 3

Hafthor
Hafthor

Reputation: 16916

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/'

Upvotes: 10

Swastik
Swastik

Reputation: 2425

NSString *str = @"http://www.foo.com/bar/baragain"; 
NSArray *temp = [str componentsSeparatedByString: @".com"];
str = [NSString stringWithFormat: @"%@%@", [temp objectAtIndex:0], @".com"];

Upvotes: -3

Domestic Cat
Domestic Cat

Reputation: 1434

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

Upvotes: 17

Related Questions