[Swift] URL, URLComponents
2023. 12. 30. 13:55
URL
let urlString = "https://ios-development.tistory.com/search/users?id=123&age=20"
let url = URL(string: urlString)
/// 주소 전체 "https://ios-development.tistory.com/search/users?id=123&age=20"
print(url?.absoluteURL)
/// 어떤식으로 네트워킹 하는지 "https"
print(url?.scheme)
/// baseURL과 같이 메인 주소 "ios-development.tistory.com"
print(url?.host)
/// host뒤에 query parameter를 제외한 주소 "/search/users"
print(url?.path)
/// query parameter 값 "id=123&age=20"
print(url?.query)
/// 설정하지 않으면 디폴트는 nil
print(url?.baseURL)
let url = "https://api.openweathermap.org/data/2.5/forecast"
let param = ["lat" : "\(latitude)",
"lon" : "\(longitude)",
"appid" : weatherAPIKey,
"lang" : "kr",
"cnt" : "10",
"units" : "metric"
]
AF.request(url, method: .get, parameters: param)
.responseData(completionHandler: { response in
switch response.result{
case let .success(data):
do{
let decoder = JSONDecoder()
let result = try decoder.decode(WeatherInfomation.self, from: data)
completionHandler(.success(result))
}
catch{
completionHandler(.failure(error))
}
case let .failure(error):
completionHandler(.failure(error))
}
}).resume()
URLComponents
// https://ios-development.tistory.com/search/users?id=123&age=20
var urlComponents = URLComponents(string: "https://ios-development.tistory.com/search/users?")
// query 설정
let userIDQuery = URLQueryItem(name: "id", value: "123")
let ageQuery = URLQueryItem(name: "age", value: "20")
urlComponents?.queryItems?.append(userIDQuery)
urlComponents?.queryItems?.append(ageQuery)
/// 전체 경로 (문자열이 아닌 형태) https://ios-development.tistory.com/search/users?id=123&age=20
print(urlComponents?.url)
/// "https://ios-development.tistory.com/search/users?id=123&age=20"
print(urlComponents?.string)
/// [id=123, age=20]
print(urlComponents?.queryItems)
static let scheme = "https"
static let host = "dapi.kakao.com"
static let path = "/v2/search/"
func searchBlog(query: String) -> URLComponents {
var components = URLComponents()
components.scheme = SearchBlogAPI.scheme
components.host = SearchBlogAPI.host
components.path = SearchBlogAPI.path + "blog"
components.queryItems = [
URLQueryItem(name: "query", value: query),
URLQueryItem(name: "size", value: "25")
]
return components
}
728x90
'iOS > Swift' 카테고리의 다른 글
[iOS] QR코드 리더기 (0) | 2024.01.06 |
---|---|
[iOS] LocalAuthentication (0) | 2024.01.06 |
[Swift] Dispatch (1) (0) | 2023.11.23 |
[Swift] RelativeDateTimeFormatter(상대시간) (0) | 2023.11.20 |
[Swift] 공식문서 파헤치기 (Array, Set, Dictionary) (0) | 2023.11.11 |