URL(URI)を各要素に分割して処理する場合に、NSURLのリファレンスの説明が不十分なので要約。というかリファレンス読む人は全員RFC1808熟知しているよねって前提なんですかね?
NSURLの各要素を取り出すメソッドには以下のようなものがある。
– absoluteString
– absoluteURL
– baseURL
– fragment
– host
– lastPathComponent
– parameterString
– password
– path
– pathComponents
– pathExtension
– port
– query
– relativePath
– relativeString
– resourceSpecifier
– scheme
– standardizedURL
– user
このうちURLの表現を変えたもの(standardizedURL,absoluteURL)、パスの表現を変えたもの(absoluteString,relativeString,relativePath)は今回は省略。
また baseURL は URLWithString:relativeToURL: などで作った時に指定したbaseURLで相対パスも省略。あくまでも分解して各要素を取り出して使うための調査。
ただし、xxxString,とxxxPathの違いはString>PathでPathはスキーマやホスト部を除いた部分にあたるのでPathは使うことがあるかもしれない。
上記のメソッドのそれぞれで下記の各要素が取り出せる。
<scheme>://<user>:<password>@<host>:<port>/<path>;<parameterString>?<query>#<fragment>
なお path については 先頭の"/"を含む形になる。resourceSpecifier は "≶scheme>:"を除いた部分のすべて。
pathComponentsはpathを"/"で区切った各要素毎(NSStringの同名のメソッドと同等)、lastPathComponentは最後のパス要素(NSStringの同名のメソッドと同等)、pathExtensionはlastPathComponentの拡張子部分(NSStringの同名のメソッドと同等)。
となる、例をあげると以下のようになる。
"http://www.apple.com/"
scheme = http
host = www.apple.com
"http://www.apple.com/jp/osx/"
scheme = http
host = www.apple.com
path = /jp/osx/
lastPathComponent = osx
"https://guest:anonymous@localhost:8080/tmp/folder"
scheme = https
host = localhost
path = /tmp/folder
lastPathComponent = folder
user = guest
password = anonymous
port = 8080
"http://server1/cgi-bin/getlist.php;product?id=123456&sort=1#tag1"
scheme = http
host = server1
path = /cgi-bin/getlist.php
lastPathComponent = getlist.php
pathExtension = php
parameterString = product
query = id=123456&sort=1
fragment = tag1
resourceSpecifier = //server1/cgi-bin/getlist.php;product?id=123456&sort=1#tag1
注目はqueryが中身をそれ以上分解してくれないこと。&で区切って属性と値を=で結ぶという書き方は規格外とのこと。もしこういう形でURLを組み立てて値を取り出そうとしたら自分で実装しなければならない。perlとかphpではAPIが用意よされていたと思うんだがなぁ。
あとparameterStringは見たことがなかった。たまには規格に目を通すべきですね。
確認用のコードをgistに置いてみた。gistってこんな風に使うのであっているのかな?
posted by 永遠製作所 at 16:15| 東京 ☀|
Comment(0)
|
TrackBack(0)
|
Cocoa
|

|