Get parts of a NSURL in objective-c

I have an NSString with the value of

http://digg.com/news/business/24hr

How can I get everything before the 3rd level?

http://digg.com/news/
67998 次浏览

提醒你一下,这并不是第三个层次。 URL 是这样分割的:

  • 协议或方案(这里是 http)
  • ://分界线
  • the username and the password (here there isn't any, but it could be username:password@hostname)
  • 主机名(这里是 digg.com)
  • 端口(例如域名后面的 :80)
  • 路径(这里,/news/business/24hr)
  • 参数字符串(分号后面的任何东西)
  • 查询字符串(如果使用诸如 ?foo=bar&baz=frob之类的 GET 参数,就会使用这个字符串)
  • the fragment (that would be if you had an anchor in the link, like #foobar).

A "fully-featured" URL would look like this:

http://foobar:nicate@example.com:8080/some/path/file.html;params-here?foo=bar#baz

NSURL具有广泛的访问器。您可以在 NSURLAccessing the Parts of the URL部分的文档中检查它们。参考一下:

  • 美国广播公司(-[NSURL scheme]) = http://www.com.cn
  • -[NSURL resourceSpecifier] = (从//到 URL 末尾的所有内容)
  • -[NSURL user] = foobar
  • -[NSURL password] = nate
  • -[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] = params-here
  • -[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,您似乎需要的是协议、主机和第一个路径组件。(-[NSString pathComponents]返回的数组中位于索引0处的元素只是“/”,因此需要位于索引1处的元素。其他的斜线被丢弃。)

Using Playground , language swift, I got this ! Playground provides an interactive way of seeing this in action. I hope you can enjoy doing the same, a fun way to learn NSURL an important topic in iOS.