在 Objective-C 中获取 NSURL 的一部分
我有一个 NSString,其值为
http://digg.com/news/business/24hr
How can I get everything before the 3rd level?
http://digg.com/news/
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/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,这不完全是第三层。 URL 的分割方式如下:
http
)、://
分隔符、username:password@hostname
)digg.com
):80
之后例如域名)/news/business/24hr
)?foo=bar&baz=frob
)#foobar
)。一个“功能齐全”的 URL 看起来像这样:
NSURL
具有广泛的访问器。您可以在NSURL
类,访问 URL 的各个部分部分。快速参考:-[NSURL schema]
= http-[NSURL resourceSpecifier]
=(从 // 到 URL 末尾的所有内容)-[NSURL user ]
= foobar-[NSURL 密码]
= nicate-[NSURL 主机]
= example.com-[NSURL 端口]
= 8080-[NSURL lastPathComponent]
= file.html-[NSURL pathExtension]
= html- [NSURL参数字符串]
= params-here-[NSURL查询]
= foo=bar-[NSURL片段]
= baz不过,你想要什么,是这样的:
对于您的示例 URL,您似乎想要的是协议、主机和第一个路径组件。 (
-[NSString pathComponents]
返回的数组中索引 0 处的元素只是“/”,因此您需要索引 1 处的元素。其他斜杠将被丢弃。)This isn't exactly the third level, mind you. An URL is split like that way:
http
)://
delimiterusername:password@hostname
)digg.com
):80
after the domain name for instance)/news/business/24hr
)?foo=bar&baz=frob
)#foobar
).A "fully-featured" URL would look like this:
NSURL
has a wide range of accessors. You may check them in the documentation for theNSURL
class, section Accessing the Parts of the URL. For quick reference:-[NSURL scheme]
= http-[NSURL resourceSpecifier]
= (everything from // to the end of the URL)-[NSURL user]
= foobar-[NSURL password]
= nicate-[NSURL host]
= example.com-[NSURL port]
= 8080-[NSURL path]
= /some/path/file.html-[NSURL pathComponents]
= @["/", "some", "path", "file.html"] (note that the initial / is part of it)-[NSURL lastPathComponent]
= file.html-[NSURL pathExtension]
= html-[NSURL parameterString]
= params-here-[NSURL query]
= foo=bar-[NSURL fragment]
= bazWhat you'll want, though, is something like that:
For your example URL, what you seem to want is the protocol, the host and the first path component. (The element at index 0 in the array returned by
-[NSString pathComponents]
is simply "/", so you'll want the element at index 1. The other slashes are discarded.)Playground 提供了一种交互式方式来查看其实际情况。我希望你能喜欢做同样的事情,这是学习 NSURL(iOS 中的一个重要主题)的有趣方式。
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.