2010-11-24 65 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:@""];