JY-CONTENTS

JY

JY-CONTENTS
search

+

MENU

【Swift】URLのクエリストリングを追加

【Swift】URLのクエリストリングを追加

(DATE)

-

2018.11.23

(CATEGORY)

-

「https://api.github.com/search/repositories」を
「https://api.github.com/search/repositories?q=swift」にする。

import Foundation

let url: URL = URL(string: "https://api.github.com/search/repositories")!

//“URLComponents型の値を生成
var components = URLComponents(url: url, resolvingAgainstBaseURL: true)!

//[URLQueryItem]型の値にしてURLComponents型のqueryItemsプロパティにセット
//public var queryItems: [URLQueryItem]?
components.queryItems = [URLQueryItem(name: "q", value: "swift")]

print(components) //https://api.github.com/search/repositories?q=swift

サンプル

import Foundation

//HTTPメソッドの定義
enum method {
    case get
    case post
}

//検索キーワード
let keyword: String = "swift"
//表示ページ数
let perPage = 2
//HTTPメソッド「get」を指定
let met = method.get
var baseURL: URL = URL(string: "https://api.github.com")!
var path:String = "/search/repositories"
var parameters: Any? = ["q": keyword, "per_page": perPage]

//baseURLとpathを連結
let url = baseURL.appendingPathComponent(path)
var components = URLComponents(url: url, resolvingAgainstBaseURL: true)

switch met {
    case .get:
        //parametersをダウンキャスト
        let dictionary = parameters as? [String : Any]
        //parametersを元にURLQueryItemのインスタンスを生成、取得(配列)
        let queryItems = dictionary?.map { key, value -> URLQueryItem in
            return URLQueryItem(
                name: key,
                value: String(describing: value)
            )
        }
        //クエリストリングを追加
        components?.queryItems = queryItems
    
    default:
        fatalError("Unsupported method")
}

print(components!) //https://api.github.com/search/repositories?q=swift&per_page=2

NEW TOPICS

/ ニュー & アップデート

SEE ALSO

/ 似た記事を見る

JY CONTENTS UNIQUE BLOG

search-menu search-menu