URL의 기본 구조
https://www.example.com:443/path?query=1#fragment
Scheme: 프로토콜 (
https
,http
등)Host: 서버 주소 (
www.example.com
)Port: 통신 포트 (
443
,80
등)Path: 리소스 경로 (
/path
)Query: 쿼리 파라미터 (
?query=1
)Fragment: 해시값 (
#fragment
)
REST API
REST(Representational State Transfer): 웹 서비스를 위한 아키텍처 스타일
HTTP 메서드:
GET
: 데이터 조회POST
: 데이터 생성PUT
: 데이터 수정DELETE
: 데이터 삭제
URLSession
URLSession은 네트워크 요청을 처리하는 API로, REST API와 통신할 때 사용한다.
GET 요청 예제
import Foundation func fetchData() { let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! let task = URLSession.shared.dataTask(with: url) { data, response, error in if let data = data { let json = try? JSONSerialization.jsonObject(with: data, options: []) print(json ?? "데이터 없음") } } task.resume() }
POST 요청 예제
import Foundation func postData() { let url = URL(string: "https://jsonplaceholder.typicode.com/posts")! var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let body: [String: Any] = ["title": "foo", "body": "bar", "userId": 1] request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: []) let task = URLSession.shared.dataTask(with: request) { data, response, error in if let data = data { let json = try? JSONSerialization.jsonObject(with: data, options: []) print(json ?? "응답 없음") } } task.resume() }