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