Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What is going on with this article?
@shtnkgm

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

More than 1 year has passed since last update.

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
5
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
yahoo-japan-corp
Yahoo! JAPAN を運営しています。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
5
Help us understand the problem. What is going on with this article?