ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Post API 호출예
    GET & POST 2022. 7. 12. 16:25

    import UIKit

     

     

    func makePostRequest(){

        

        guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {

            return

        }

        

        print("Ready...")

        var request = URLRequest(url: url)

        //method, body, headers

        request.httpMethod = "POST"

        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        

        let body : [String: AnyHashable] = [

            "userId" : 1,

            "title" : "test",

            "body" : "body1234"

        

        ]

        request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed)

        

        //Make the request

        let task = URLSession.shared.dataTask(with: request){ data, _, error in

            guard let data = data, error == nil else {

                return

            }

            

            do{

                

                //let response = try JSONSerialization.jsonObject(with: data, options: .allowFragments)

                let response = try JSONDecoder().decode(Response.self, from: data)

                print("성공 : \(response)")

                

            } catch {

                print(error)

            }

            

        }

        task.resume()

    }

     

    struct Response: Codable{

        let body:String

        let id: Int

        let title:String

        let userId: Int

    }

     

    makePostRequest()

    'GET & POST' 카테고리의 다른 글

    Alamofire, Combine으로 POST 데이터 불러오기  (0) 2022.07.15
    SwiftUI GET & POST request, 예제 1  (0) 2022.06.29

    댓글

Designed by Tistory.