투케이2K

319. (ios/swift) URLSession Http 요청 수행 및 Codable 코더블 사용해 response 응답 json 데이터 디코딩 실시 본문

IOS

319. (ios/swift) URLSession Http 요청 수행 및 Codable 코더블 사용해 response 응답 json 데이터 디코딩 실시

투케이2K 2022. 11. 22. 15:26
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT

 

[소스 코드]

    // MARK: - [Codable (코더블) 사용해 json 데이터 파싱]
    struct jsonDecodeStruct : Codable {
        
        // [전역 변수 선언 실시]
        var userId : Int
        var id : Int
        
        // [구조체 생성자 초기화 실시]
        init(userId: Int, id: Int, phone: String, sex: Bool){
            // [전역 변수 = 인풋 값]
            self.userId = userId
            self.id = id
        }
    }

    
    
    
    
    
    
    // MARK: - [테스트 메인 함수 정의 실시]
    func testMain() {
        
        // [로직 처리 수행]
        DispatchQueue.main.async {
            
            // [URL 지정 및 파라미터 값 지정 실시]
            let urlComponents = URLComponents(string: "https://jsonplaceholder.typicode.com/posts")
            let dicData = ["userId":1, "id":1] as Dictionary<String, Any>? // 딕셔너리 사용해 json 데이터 만든다
            let jsonData = try! JSONSerialization.data(withJSONObject: dicData!, options: [])
            
            
            // [http 통신 타입 및 헤더 지정 실시]
            var requestURL = URLRequest(url: (urlComponents?.url)!)
            requestURL.httpMethod = "POST" // POST
            requestURL.addValue("application/json", forHTTPHeaderField: "Content-Type") // POST
            requestURL.httpBody = jsonData // Body 부분에 Json 데이터 삽입 실시

            
            // [http 요쳥을 위한 URLSessionDataTask 생성]
            print("")
            print("====================================")
            print("[requestPOST_BODY_JSON : http post body json 요청 실시]")
            print("url : ", requestURL)
            print("json : ", String(data: jsonData, encoding: .utf8) ?? "")
            print("====================================")
            print("")
            let dataTask = URLSession.shared.dataTask(with: requestURL) { (data, response, error) in

                // [error가 존재하면 종료]
                guard error == nil else {
                    print("")
                    print("====================================")
                    print("[requestPOST_BODY_JSON : http post body json 요청 실패]")
                    print("fail : ", error?.localizedDescription ?? "")
                    print("====================================")
                    print("")
                    return
                }

                // [status 코드 체크 실시]
                let successsRange = 200..<300
                guard let statusCode = (response as? HTTPURLResponse)?.statusCode, successsRange.contains(statusCode)
                else {
                    print("")
                    print("====================================")
                    print("[requestPOST_BODY_JSON : http post body json 요청 에러]")
                    print("error : ", (response as? HTTPURLResponse)?.statusCode ?? 0)
                    print("msg : ", (response as? HTTPURLResponse)?.description ?? "")
                    print("====================================")
                    print("")
                    return
                }

                // [response 데이터 획득, json 디코딩]
                let status = (response as? HTTPURLResponse)?.statusCode ?? 0
                
                do {
                    
                    // [struct 객체에 매핑 실시]
                    let response = try JSONDecoder().decode(jsonDecodeStruct.self, from: data!)
                    print("")
                    print("====================================")
                    print("[requestPOST_BODY_JSON : http post body json 응답 확인]")
                    print("status :: \(status)")
                    print("userId :: \(response.userId)")
                    print("id :: \(response.id)")
                    print("====================================")
                    print("")
                    
                } catch {
                    print("")
                    print("====================================")
                    print("[requestPOST_BODY_JSON : response json parsing error]")
                    print("error :: \(error.localizedDescription)")
                    print("====================================")
                    print("")
                }
            }

            // network 통신 실행
            dataTask.resume()

            
        }

    }
 

[결과 출력]

 

 
반응형
Comments