iOS Swift/iOS Swift - 예제

[iOS/Swift] URLSession 사용한 Rest Api 네트워크 통신 예제

주니어코더 2023. 3. 30. 15:27

 

 

 

 

 

 

 

URLSession

Rest Api 네트워크 통신

 

 


 

 

 

⭐️ iOS에서 네트워크 통신하기 ⭐️

 

Swift 네트워크 통신 방법 중,

가장 기본적인 방법인 URLSession을 사용해보자!

 

 

 

URLSession 통신 순서는 간략히 4단계로 구성된다.

 

1. URL 객체를 생성한다.

2. Request 객체를 생성한다.

3. URLSession을 이용하여 데이터 전달

4. URLSessionTask로 작업을 나타낸다.

 

 

 

 

 

👇👇👇 URLSession에 대해 더 자세히 알고 싶다면? 👇👇👇

 

2023.02.28 - [iOS Swift/iOS Swift - 기초] - [iOS/Swift] URLSession Task 네트워크 api 통신

 

[iOS/Swift] URLSession Task 네트워크 api 통신

Swift 네트워크 통신 feat. URLSession , URLSessionTask iOS에서 http 네트워크 통신을 위해서는 URLSession과 URLSessionTask 를 사용해야 한다! 라이브러리인 Alamorfire와 moya 도 URLSession을 래핑한것으로 URLSession을

ohwhatisthis.tistory.com

 

 

 

 

 

Chap1.  URLComponents를 이용한 URL 생성


 

🔎   URLComponents  이란?

: URLComponents는 URL을 구성하는 구조이며 URL을 더 쉽게 생성하게 도와준다

 

 

URLComponents를 사용하는 이유를 설명하기 전 코드 먼저 살펴보자 ~!

 

import Foundation

// URLComponents를 사용하여 URL 구성
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = "www.example.com"
urlComponents.path = "/api/v1/users"
urlComponents.queryItems = [
    URLQueryItem(name: "page", value: "1"),
    URLQueryItem(name: "per_page", value: "10")
]

// URL 구성 요소를 사용하여 URL 생성
if let url = urlComponents.url {
    print("URL: \(url)") // 출력: "URL: https://www.example.com/api/v1/users?page=1&per_page=10"
}

 

 

URLComponents는 scheme/host/path/queryItems로 나눠져 있다

 

위 코드에서 출력된 url 주소를 보면

"https://www.example.com/api/v1/users?page=1&per_page=10"가 출력된다

 

직접 URL을 작성하여도 되지만 path와 queryItem 가 바뀔 때마다 전체 주소를 변경한다면 번거롭겠죠?

 

하지만 URLComponents를 사용하여 따로 관리한다면? 변경되는 부분만 수정하면 된다!

 

 

 

 

 

Chap2.  URLRequest 객체를 생성


 

URLRequest는 URL에 대한 요청을 나타내는 인스턴스이다!

 

URLRequest는 URL요청에 필요한 정보를 포함시키며, 아래와 같은 구성요소가 있다

 

 

🔎   URLRequest  구성 요소

  • url: 요청의 대상 URL
  • httpMethod: 요청에 사용되는 HTTP 메서드 (예: "GET", "POST", "PUT", "DELETE" 등)
  • allHTTPHeaderFields: 요청의 모든 HTTP 헤더 필드를 포함하는 딕셔너리
  • httpBody: 요청의 HTTP 본문
  • cachePolicy: 요청에 사용되는 캐시 정책
  • timeoutInterval: 요청의 타임아웃 시간 (초)

 

 

위에서 만든 URL에 method/header/body를 추가해보자!

 

위에서 만든 URL 코드에 이어 URLRequset 코드를 작성

 

import Foundation

// URLComponents를 사용하여 URL 구성
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = "www.example.com"
urlComponents.path = "/api/v1/users"
urlComponents.queryItems = [
    URLQueryItem(name: "page", value: "1"),
    URLQueryItem(name: "per_page", value: "10")
]

// URL 구성 요소를 사용하여 URL 생성
if let url = urlComponents.url {
    print("URL: \(url)") // 출력: "URL: https://www.example.com/api/v1/users?page=1&per_page=10"
}

// URLRequest 인스턴스 생성
var request = URLRequest(url: url)
request.httpMethod = "POST" // 요청에 사용할 HTTP 메서드 설정

// HTTP 헤더 설정
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

// HTTP 바디 설정
let body = [
    "title": "My first post",
    "body": "This is the content of my first post",
    "userId": 1
] as [String: Any]

do {
    request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])
} catch {
    print("Error creating JSON data")
}

 

 

 

 

 

Chap3.  URLSession을 이용하여 요청과 응답 처리


 

 

위에서 URL 생성과, 필요한 정보를 담았다면 이제 요청을 할 차례!

 

Swift에서는 URLSession을 사용하여 요청한다

 

URLSession에서 URL에 요청을 한 후 dataTask에서 응답이 오면 코드를 수행한다

 

위에서 생성한 URL을 요청한 후 응답을 처리해보자!

 

import Foundation

// URLComponents를 사용하여 URL 구성
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = "www.example.com"
urlComponents.path = "/api/v1/users"
urlComponents.queryItems = [
    URLQueryItem(name: "page", value: "1"),
    URLQueryItem(name: "per_page", value: "10")
]

// URL 구성 요소를 사용하여 URL 생성
if let url = urlComponents.url {
    print("URL: \(url)") // 출력: "URL: https://www.example.com/api/v1/users?page=1&per_page=10"
}

// URLRequest 인스턴스 생성
var request = URLRequest(url: url)
request.httpMethod = "POST" // 요청에 사용할 HTTP 메서드 설정

// HTTP 헤더 설정
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

// HTTP 바디 설정
let body = [
    "title": "My first post",
    "body": "This is the content of my first post",
    "userId": 1
] as [String: Any]

do {
    request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])
} catch {
    print("Error creating JSON data")
}

// URLSession을 사용하여 요청 수행
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
    } else if let data = data, let response = response as? HTTPURLResponse, response.statusCode == 201 {
        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                print("JSON Response: \(json)")
            }
        } catch {
            print("Error parsing JSON response")
        }
    } else {
        print("Unexpected error")
    }
}

task.resume() // 작업 시작

 

 

 

 

 

결론


 

네트워크 통신 과정의 흐름

 

URL생성 → URL에 요청할 정보 입력 → 해당 URL에 작업 요청 → 작업이 완료된 후 응답 처리

 

 

 

 

 

 

 

 

 

 

 

반응형