Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 从NSString或NSUrl获取网站的根目录_Ios_Cocoa_Nsurl - Fatal编程技术网

Ios 从NSString或NSUrl获取网站的根目录

Ios 从NSString或NSUrl获取网站的根目录,ios,cocoa,nsurl,Ios,Cocoa,Nsurl,知道如何从NSString或NSURL获取网站的根目录吗?所以如果我的URL是http://www.foo.com/bar/baragain我将如何获得http://www.foo.com/?使用[url方案]和[url主机]如下: NSURL *url = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"]; NSLog(@"Base url: %@://%@", [url scheme], [url host]); // outp

知道如何从NSString或NSURL获取网站的根目录吗?所以如果我的URL是http://www.foo.com/bar/baragain我将如何获得http://www.foo.com/

使用
[url方案]
[url主机]
如下:

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

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

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

谁能让我知道为什么我的回答被否决了?这是错误的,想象一下像
http://www.computer.com/
顺便说一句,不是我。雪莉,我没有投你反对票。虽然我同意fluchtpunkt,但是你的解决方案除了.com之外不能解决任何问题。但是,我不太清楚我的问题中是否需要它。我举的这个例子可能会让你觉得我只想把它用于.com。那很好。我也在学习过程中。我感谢大家在这里纠正我们,如果我们错了,那么好的解决方案应该能够解决类似
ftp://user:pass@无论如何。here.host.org:8080
。这不是通用的,因为也可以有用户名和密码……这是更好的解决方案:“我发现的另一种方法是NSURL包含一个path方法。我可以获取路径,然后从完整URL中减去它,我就可以得到我想要的了。”是的,如果路径中有端口,减去路径会更安全!谢谢。@Haftor你是对的-这仍然是错误的。请随意编辑。
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/'
NSString *urlString = @"http://www.foo.com/bar/baragain";
NSURL *rootUrl = [NSURL URLWithString:urlString];
NSString *rootUrlString = [urlString stringByReplacingOccurrencesOfString:rootUrl.path withString:@""];