2010-11-24 59 views

回答

15

通过使用[url scheme][url host]像这样:

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

这不是普遍的,因为这样可能的用户名和密码太... 这是更好的解决方案:“我发现,这样做的另一种方式是NSURL包含路径方法。我可以得到路径,并从完整的URL中减去它,并且剩下我想要的东西。“ – Renetik 2012-12-21 09:50:10

+1

是的,减去路径更安全以防在其中存在端口 – petenelson 2013-03-01 11:49:45

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

任何人都可以请让我知道对我进行downvoting我的回答 – Swastik 2010-11-24 05:17:52

+0

upvoted ............. – Bourne 2010-11-24 06:30:09

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

可以删除NSURLpath从字符串。这说明了端口号和作为根站点一部分的其他数据。

NSString *urlString = @"http://www.foo.com/bar/baragain"; 
NSURL *rootUrl = [NSURL URLWithString:urlString]; 
NSString *rootUrlString = [urlString stringByReplacingOccurrencesOfString:rootUrl.path withString:@""];