Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

nsstring - 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/
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This isn't exactly the third level, mind you. An URL is split like that way:

  • the protocol or scheme (here, http)
  • the :// delimiter
  • the username and the password (here there isn't any, but it could be username:password@hostname)
  • the host name (here, digg.com)
  • the port (that would be :80 after the domain name for instance)
  • the path (here, /news/business/24hr)
  • the parameter string (anything that follows a semicolon)
  • the query string (that would be if you had GET parameters like ?foo=bar&baz=frob)
  • 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:[email protected]:8080/some/path/file.html;params-here?foo=bar#baz

NSURL has a wide range of accessors. You may check them in the documentation for the NSURL 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] = baz

What you'll want, though, is something like that:

NSURL* url = [NSURL URLWithString:@"http://digg.com/news/business/24hr"];
NSString* reducedUrl = [NSString stringWithFormat:
    @"%@://%@/%@",
    url.scheme,
    url.host,
    url.pathComponents[1]];

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...