관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] URL, URI 파싱, path, query string (URLComponents, URITemplate 프레임워크) 본문

iOS 응용 (swift)

[iOS - swift] URL, URI 파싱, path, query string (URLComponents, URITemplate 프레임워크)

jake-kim 2021. 1. 25. 23:25

URL에 parameter 삽입 (query string)

  • "https://domainABC" 를 "https://domainABC?memberID=1234"로 변경
let url = "https://domainABC"
var components = URLComponents(string: url)
let id = URLQueryItem(name: "memberID", value: "1234")
components?.queryItems = [id]

guard let newURL = components?.url else {
    return
}
print(newURL) // Optional(https://domainABC?memberID=1234)

URL의 parameter 파싱 (query string)

  • "https://domainABC?memberID=1234"를 memberID 데이터만 획득
let url = "https://domainABC?memberID=1234"
let components = URLComponents(string: url)
let items = components?.queryItems ?? []
for item in items {
    print("\(item.name), \(item.value)") // memberID, Optional("1234")
}

URL의 path에 "{}" 형식으로 내려오는 url 파싱

  • "https://domainABC/{id}/{scope}"를 id, scope값에 각각 값을 채워서 삽입
let url = "https://domainABC/{id}/{scope}/"
let template = URITemplate(template: url)
let newURL = template.expand(["id": "123", "scope": "inHouse"])
print(newURL) // https://domainABC/123/inHouse/
print(template.variables) // ["id", "scope"]
Comments