-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudy2_URLComponents.swift
More file actions
52 lines (43 loc) · 2.73 KB
/
Copy pathStudy2_URLComponents.swift
File metadata and controls
52 lines (43 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//
// StudyCode2_URLComponents.swift
// CodeStudy
//
// Created by Shinya Ikehara on 2026/01/24.
//
import Foundation
struct Study2 {
//URLの主なパーツ
//「scheme」 読み方「スキーム」 "http://"や"https://"などの”どんな手段で通信するのか?”を指している。
//「host」 google.comやyoutube.com、Qiita.comなどの通信元
//「path」 通信元のサイトが枝分かれする際の道順 Qiitaならスキームとhostを入れ、"/estel" でestelのアカウントを表示、"/estel/follwers"でestelのフォロワー表示など
//「query」 ?以降のオプション指定
//「fragment」
private let URLString = "scheme://host/path?query#fragment"
//Study1_URL
private let baseURL = URL(string: "scheme://host")!
//「.appending」とはURLの拡張機能の一つ、URLの後ろにpathを追加できる pathの型はstring
//.appendingでbaseURLに後ろの道順を作ってあげる
//pathは変数・定数に.appending(path: "文字列")でつくる
//ここまででpathURLには「scheme://host/path」までが入っている
private var pathURL: URL {
baseURL.appending(path: "path")
}
func makeURL() -> URL? {
//「URLComponents」 は主にqueryを安全につける時(クエリをつけるなら実務ではほぼ必須)に使用するキーワード
//入力されたURLを部品として分解することができる
//initとして(url: URL ,resolvingAgainstBaseURL: Bool)がある
//「resolvingAgainstBaseURL」はtrueだと、入力されたURLが相対URLの場合、resolveURLでbaseURLと解決してから分解すること ほとんどの場合ここは絶対URLが入るのでfalse
var urlComponents = URLComponents(url: pathURL, resolvingAgainstBaseURL: false)
//「queryItems」 配列で[URLQueryItem]を渡すためのURLComponentsが持っているキーワード
//[URLQueryItem]は配列順にURLComponents()のurlの後ろに付け足す
//URLQueryItemはinitとして(name: string, value: string)を持っており、それがそのまま足されるこのコードだと"?query=value"
urlComponents?.queryItems = [
URLQueryItem(name: "query", value: "value")
]
//URLComponentsの「.url」でqueryを含めたURLの組み立てを行う
//.urlは組み立て時にURL?のOptionalで渡される(pathURL)が不正またはnilの場合があり、URLComponentsが正しく分解できない時があるため
//通常はthrows/throwとguardを使いErrorが出ない場合にreturnで返す
let url = urlComponents?.url
return url
}
}