はじめに
現在、ウィジェットを使用するアプリを作成しています。
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拡張にしておくと再利用するときに便利です。