// get 요청
import Foundation
func fetchAPIData() {
let urlString = "https://jsonplaceholder.typicode.com/posts"
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print("Response JSON: \(json)")
} catch {
print("Failed to parse JSON: \(error.localizedDescription)")
}
}
task.resume()
}
fetchAPIData()
// post 요청
import Foundation
func sendDataToAPI() {
let urlString = "https://jsonplaceholder.typicode.com/posts"
guard let url = URL(string: urlString) else { return }
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)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}
if let data = data, let responseString = String(data: data, encoding: .utf8) {
print("Response: \(responseString)")
}
}
task.resume()
}
sendDataToAPI()
프로젝트에서 Alamofire을 설치하고 사용
https://github.com/Alamofire/Alamofire
// Alamofire GET 요청
import Alamofire
func fetchAPIDataWithAlamofire() {
let url = "https://jsonplaceholder.typicode.com/posts"
AF.request(url).responseJSON { response in
switch response.result {
case .success(let data):
print("Response JSON: \(data)")
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}
}
fetchAPIDataWithAlamofire()
// Alamofire POST 요청
import Alamofire
func sendDataToAPIWithAlamofire() {
let url = "https://jsonplaceholder.typicode.com/posts"
let parameters: [String: Any] = ["title": "foo", "body": "bar", "userId": 1]
AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success(let data):
print("Response JSON: \(data)")
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}
}
sendDataToAPIWithAlamofire()
URLSession은 기본적으로 사용 가능하며 추가 의존성이 없다. 간단한 작업에 적합하다
Alamofire은 더 간편하고, 다양한 기능을 제공한다. 프로젝트 규모가 크거나 복잡한 네트워크 요청이 많을 경우 사용하면 유리합니다.
Codable을 활용해 API응답을 Swift 모델로 변환하면 더 깔끔하게 처리할 수 있다.