Danny의 iOS 컨닝페이퍼
article thumbnail

URL

URL은 특정 리소스의 위치를 나타냅니다.

 

보통 Sring을 통하여 접근합니다.

 

영어나 특수한 문자만 사용이 가능하고

한글이나 공백을 포함 시 리턴값이 nil이 나오게 됩니다.

let urlStr = "https://ios-daniel-yang.tistory.com/search?keyword=iOS&page=1"
let url = URL(string: urlStr)!

 

만약 URL에 한글 및 공백이 필요한 경우에는

String.addingPercentEncoding 변환을 통해 사용이 가능한데요.

 

[iOS/Swift] addingPercentEncoding (URL이 nil 일 경우, URL Encoding, CharacterSet) 를 참고해 주세요.

 

구조

scheme 

접근할 방법을 정의해 둔 프로토콜

 

host 

접근할 서버의 호스트 이름

 

path 

호스트에서 제공하는 리소스의 경로

 

query

요청받을 리소스의 범위좁히기 위해 사용. (파라미터)

Query는 질문 형식인 "?" 뒤에 연결되는 name-value의 쌍으로 구성돼 있습니다. 

또한 엠퍼센드(&)를 통해 여러 Query도 추가 가능하죠.

 

 

이를 통해 각각의 속성에 접근해 읽기가 가능합니다.

url.absoluteURL    // "https://ios-daniel-yang.tistory.com/search?keyword=iOS&page=1"
url.scheme         // "https"
url.host           // "ios-daniel-yang.tistory.com"
url.path           // "/search"
url.query          // "keyword=iOS&page=1"

 

 

URLComponents

URL을 구성하는 구조입니다.

 

URL의 구성요소들은 오직 읽기밖에 안 됐지만,

URLComponents는 읽기쓰기가 가능하여 조금 더 유동적인 사용이 가능해지죠.

 

 

기본적인 사용방법은 동일합니다.

URLComponents의 프로퍼티 url을 통해 만들어진 URL 호출이 가능합니다.

let urlStr = "https://ios-daniel-yang.tistory.com/search?keyword=iOS&page=1"
var components = URLComponents(string: urlStr)!

components.absoluteURL    // "https://ios-daniel-yang.tistory.com/search?keyword=iOS&page=1"
components.scheme         // "https"
components.host           // "ios-daniel-yang.tistory.com"
components.path           // "/search"
components.query          // "keyword=iOS&page=1"

components.url
// https://ios-daniel-yang.tistory.com/search?keyword=iOS&page=1

 

URLComponents는 읽기 + 쓰기가 가능하기 때문에

이와 같이 표현도 가능하죠.

var components = URLComponents()
components.scheme = "https"
components.host = "ios-daniel-yang.tistory.com"
components.path = "/search"
components.query = "keyword=iOS&page=1"

components.url
// https://ios-daniel-yang.tistory.com/search?keyword=iOS&page=1

 

👉 또한 URLComponents에는 Query 파라미터를 깔끔하고 쉽게 다룰 수 있는

URLQueryItem이 있습니다!

 

구조체 URLQueryItem도 Query 형식과 마찬가지로 name-value의 쌍으로 구성되어 있습니다.

각각 값을 넣어주기만 하면 OK!

 

또한 URLComponentsqueryItem은 배열형식으로 돼있어

여러 아이템을 추가해서 사용이 가능합니다.

 

바로 예제를 보시죠.

var components = URLComponents(string: "https://ios-daniel-yang.tistory.com/search")!
let keyword = URLQueryItem(name: "keyword", value: "iOS")
let page = URLQueryItem(name: "page", value: "1")
components.queryItems = [keyword, page]

components.url
// https://ios-daniel-yang.tistory.com/search?keyword=iOS&page=1

 

각각의 요소들을 분리하여 사용하고 싶은 경우

이와 같이 사용할 수 있겠죠!

var components = URLComponents()
components.scheme = "https"
components.host = "ios-daniel-yang.tistory.com"
components.path = "/search"
components.queryItems = [
    URLQueryItem(name: "keyword", value: "iOS"),
    URLQueryItem(name: "page", value: "1")
]

components.url
// https://ios-daniel-yang.tistory.com/search?keyword=iOS&page=1

 

 

부족한 설명이지만, 조금은 이해 가셨나요?

틀린 내용이 있다면 언제든지 지적해 주시면 감사히 받겠습니다. 🫠
읽어주셔서 감사합니다 😃

 

 

 

반응형
profile

Danny의 iOS 컨닝페이퍼

@Danny's iOS

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!