LoginSignup
15
9

More than 3 years have passed since last update.

[Swift 5]URLからクエリパラメータを取得する方法:URLComponentsを使用

Last updated at Posted at 2019-08-13

今回、URLスキームで渡されるクエリを使用したいために調べました。
もちろん、httpから始まるURLのクエリを取得する時にも使えます。

https://www.example.com/index.php?message=arigato
みたいなURLの時、
クエリ部分である?message=arigatoarigatoが使いたい時

// URLからURLComponentsにする
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)
    if let queryValue = urlComponents?.queryItems?.first?.value {
        print(queryValue)  // -> arigato
    }

クエリが一つだけ、もしくは1番目のものを使いたい時はこれだけでOKです。
複数のクエリがあるときは、queryItemsが配列になっているので、適切な方法でアクセスしましょう
e.g. queryItems[2]

=の左がname、右側がvalueで取得できます。

e.g. queryItems[2].name, queryItems[2].value

最初はurl.query.components(separatedBy:"=")などで文字列分割しようとしていたけど、適切な方法が見つかってよかった!^-^

参考

https://stackoverflow.com/questions/43118687/split-url-query-in-swift
https://stackoverflow.com/questions/38720933/whats-the-difference-between-passing-false-and-true-to-resolvingagainstbaseurl

15
9
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
15
9