NSURL 简记

日常应用中经常使用到 NSURL,但对 HTTP URL 构成和 API 中接口返回值并不很了解,今天记录下以备后查。

HTTP URL 可以分成如下几部分:

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

下例的URL拥有上述所有特征:

http://foobar:[email protected]:8080/some/path/file.html;params-here?foo=bar#baz

NSURL API 提供读取这些特征的方法,以上面的 URL 为例,各方法调用返回值如下:

  • -[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

需要注意的是 - pathComponents 返回的数组中,第一个部分是 /

日常开发中,我们会从已有的 URL 中取需要的部分构造新 URL:

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

参考文章:

  1. Parts of a NSURL

你可能感兴趣的:(NSURL 简记)