iOS/iOS

[iOS] 네트워크 통신 - URLSession 간단한 예제

여성일 2023. 8. 10. 17:09
728x90

이전 글에서 URLSession의 Life Cycle에 대해서 간단히 다루어봤다.

이번 글에서는 간단한 GET/POST 예제를 통해 URLSession의 Life Cycle을 풀어서 설명해보겠다.

 

🔄 URLSession Life Cycle 🔄

통신할 URL 객체, Request 객체를 생성하고 설정한다.

⬇️

URLSessionConfiguration을 통해 적절한 URLSession 인스턴스를 생성한다.

⬇️

URLSessionTask를 생성하고, 적절한 Completion Handler나 Delegate 메소드를 작성한다.

⬇️

생성한 Task 객체를 resume() 한다.

⬇️

Task가 완료되면 Completion Handler 클로저가 실행 된다.


 

URLSession Example - GET

✅ 이번 GET 예제에서 데이터는 REST API Test URL 사이트를 활용해보겠다.

- https://jsonplaceholder.typicode.com

해당 사이트의 GET 데이터이다. JSON으로 되어있다.

struct UserInfo: Codable {
    let userId: Int
    let id: Int
    let title: String
    let body: String
}

➡️ JSON 형태에 맞게 Codable 프로토콜을 상속받은 데이터 구조체를 생성한다. 

 

var successRange: Range = (200..<300)

➡️ statasCode의 성공 범위를 지정한 successRange 변수를 생성한다.

 

guard let url: URL = URL(string: "https://jsonplaceholder.typicode.com/posts") else {
        debugPrint("URL is Not Found.")
        return 
}

➡️ 통신할 URL 객체를 생성한다.

URL은 옵셔널 값이기 때문에 바인딩 해주어야한다.

 

var request: URLRequest = URLRequest(url: url)
request.httpMethod = "GET"

➡️ Requset 객체를 생성한다. 단순히 정보만 받아올 것이기 때문에 GET 메소드로 생성한다.

 

let session = URLSession(configuration: .default)

➡️ URLSessionConfiguration을 통해 적절한 URLSession 인스턴스를 생성한다.

 

session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
        guard error == nil else {
            debugPrint("Session err")
            return
        }
        
        guard let data = data else {
            debugPrint("data load err")
            return
        }
        
        if let response = response as? HTTPURLResponse {
            if successRange.contains(response.statusCode) {
                guard let responseData: [UserInfo] = try? JSONDecoder().decode([UserInfo].self, from: data) else { return }
                debugPrint(responseData[0])
            } else {
                debugPrint("Request Failed")
                return
            }
        }
    }.resume()

➡️ URLSessionTask를 생성하고, 적절한 Completion Handler나 Delegate 메소드를 작성한다.

➡️ 생성한 Task 객체를 resume() 한다.

 

실행 결과

 

 

URLSession Example - POST

✅ 이번 POST 예제에서는 reqres.in이라는 사이트를 활용해보겠다. 

여러 POST 테스트가 있지만, REGISTER - SUCCESSFUL 예제를 활용해보겠다.

❗️ 주의할 점은 요청할 때 email은 반드시 "eve.holt@reqres.in"이어야한다.

 

struct RegisterData: Codable {
    let id: Int
    let token: String
}

➡️ JSON 형태에 맞게 Codable 프로토콜을 상속받은 데이터 구조체를 생성한다. 

 

let params: [String:Any] = ["email": "eve.holt@reqres.in", "password": "test"]

➡️ 서버로 전송할 할 데이터 생성

 

guard let jsonData = try? JSONSerialization.data(withJSONObject: params, options: []) else {
    print("json err")
    return
}

➡️ 데이터를 JSON으로 encoding

 

var successRange: Range = (200..<300)

➡️ statasCode의 성공 범위를 지정한 successRange 변수를 생성한다.

 

    guard let url: URL = URL(string: "https://reqres.in/api/register") else {
        debugPrint("URL is Not Found.")
        return 
}

➡️ 통신할 URL 객체를 생성한다. 

 URL은 옵셔널 값이기 때문에 바인딩 해주어야한다.

 

var request: URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData

➡️ Requset 객체를 생성한다. 서버에 데이터를 전송해야하기 때문에 POST로 생성한다.

httpBody를 사용해서 requset 객체의 바디에 데이터를 넣는다.

 

let session = URLSession(configuration: .default)

➡️ URLSessionConfiguration을 통해 적절한 URLSession 인스턴스를 생성한다.

 

session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
        guard error == nil else {
            debugPrint("Session err")
            return
        }
        
        guard let data = data else {
            debugPrint("data load err")
            return
        }
        
        print(data)
        
        if let response = response as? HTTPURLResponse {
            if successRange.contains(response.statusCode) {
                guard let responseData: RegisterData = try? JSONDecoder().decode(RegisterData.self, from: data) else { return }
                debugPrint(responseData)
            } else {
                debugPrint("Request Failed")
                return
            }
        }
    }.resume()
}

➡️ URLSessionTask를 생성하고, 적절한 Completion Handler나 Delegate 메소드를 작성한다.

➡️ 생성한 Task 객체를 resume() 한다.

실행 결과