Answers:
请注意,这并不是第三个级别。像这样分割URL:
http)://分隔符username:password@hostname)digg.com):80在域名之后)/news/business/24hr)?foo=bar&baz=frob)#foobar)。“功能齐全”的URL如下所示:
http://foobar:nicate@example.com:8080/some/path/file.html;params-here?foo=bar#baz
NSURL有各种各样的访问器。您可以在NSURL类的文档中“ 访问URL的各个部分”中检查它们。快速参考:
-[NSURL scheme] = http-[NSURL resourceSpecifier] =(从//到URL末尾的所有内容)-[NSURL user] = foobar-[NSURL password] =尼卡特-[NSURL host] = example.com-[NSURL port] = 8080-[NSURL path] = /some/path/file.html-[NSURL pathComponents] = @ [“ /”,“ some”,“ path”,“ file.html”](请注意,开头的/是其中的一部分)-[NSURL lastPathComponent] = file.html-[NSURL pathExtension] = HTML-[NSURL parameterString] =参数-在这里-[NSURL query] = foo = bar-[NSURL fragment] = baz但是,您想要的是这样的东西:
NSURL* url = [NSURL URLWithString:@"http://digg.com/news/business/24hr"];
NSString* reducedUrl = [NSString stringWithFormat:
@"%@://%@/%@",
url.scheme,
url.host,
url.pathComponents[1]];
对于示例URL,您似乎想要的是协议,主机和第一个路径组件。(由返回的数组中索引0处的元素-[NSString pathComponents]只是“ /”,因此您需要索引1处的元素。其他斜杠将被丢弃。)
file.html项目符号中未列出该符号-我看到我们正在从路径跳转到查询字符串...
[url.pathComponents objectAtIndex:1]而不是index0,因为斜杠实际上是数组的元素,从而导致此答案中的代码输出http://digg.com//