0
1

More than 1 year has passed since last update.

【Swift】URLにパラメータを付与する

Posted at

はじめに

現在、ウィジェットを使用するアプリを作成しています。
URLSchemeにパラメータを付与して、ウィジェットからアプリにデータを渡すという仕組みにしました。
それに伴い、URLにパラメータを付与する実装を行なったので、記録しておきます。

実装

import Foundation

let baseURL = URL(string: "https://sample.com/")!

var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)

components?.queryItems = [
    URLQueryItem(name: "userName", value: "SNQ-2001"),
    URLQueryItem(name: "postCount", value: "364")
]

if let url = components?.url {
    print(url)
}

// https://sample.com/?userName=SNQ-2001&postCount=364

おわり

パラメータを付与することができました。
これをURL拡張にしておくと再利用するときに便利です。

0
1
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
0
1