14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

URLから指定したURLクエリキーの値を取得する

Last updated at Posted at 2018-12-14

URLから指定したURLクエリキーの値を取得する実装コード例です。

例) URLのidクエリ値を取得したい
https://hoge.com?name=shota&id=1234

extension URL {
    /// 指定したURLクエリパラメーターの値を取得する
    ///
    /// - Parameter key: URLクエリパラメーターのキー
    /// - Returns: 指定したURLクエリパラメーターの値(存在しない場合はnil)
    func queryValue(for key: String) -> String? {
        let queryItems = URLComponents(string: absoluteString)?.queryItems
        return queryItems?.filter { $0.name == key }.compactMap { $0.value }.first
    }
}
// 利用例
let value = URL(string: "https://hoge.com?name=shota&id=1234")?.queryValue(for: "id")
print(value!) // 1234
14
7
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
14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?