LoginSignup
41
40

More than 5 years have passed since last update.

Swift で URL クエリパラメータ を抽出する

Last updated at Posted at 2014-11-14

概要

http://hoge.com/?name1=val1&name2=val2 という URL が存在する場合に、クエリパラメータを抽出し操作したくなる場合があります。

{
    "name1": "val1",
    "name2": "val2"
}

NSURL クラスには query というメソッドが用意されており name1=val1&name2=val2 というクエリ文字列をまとめて取得することは可能ですが、個々のパラメータの抽出はできません。
さすがに正規表現で抽出するのはイケてないですね。

実装

NSURLComponents および NSURLQueryItem を利用することによって(比較的)簡単にクエリパラメータを抽出することが可能となります。

# String から NSURLComponents
let comp: NSURLComponents? = NSURLComponents(string: "http://hoge.com/?name1=val1&name2=val2")

# 操作例
for (var i=0; i < comp?.queryItems?.count; i++) {
    let item = comp?.queryItems?[i] as NSURLQueryItem
    println("name=\(item.name), value=\(item.value)")
}

# 辞書型に格納する
func urlComponentsToDict(comp:NSURLComponents) -> Dictionary<String, String> {
    var dict:Dictionary<String, String> = Dictionary<String, String>()

    for (var i=0; i < comp.queryItems?.count; i++) {
        let item = comp.queryItems?[i] as NSURLQueryItem
        dict[item.name] = item.value
    }

    return dict
}

var dict = urlComponentsToDict(comp!)

dict["name1"] // -> Some "val1"

参考

41
40
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
40