swift POST 메서드로 서버에 데이터를 어떻게 보내야 하는지 한참을 검색했다.

한참을 검색해도 답을 찾지 못하고 당일 저녁에 다시 검색해가면서 겨우겨우 해법을 구하게 됐다.

워낙에 레퍼런스는 많았지만 정작 해결은 되지 않아 정리글을 남겨두는 게 맞다고 판단해 글을 쓴다 .


다음의 openAPI 주소에 POST로 데이터를 넘겨야 하는 상황.

connect-boxoffice.run.goorm.io/comment


여기에 대한 HTTP Body(인자)로는 다음의 데이터를 넘겨야 했다.


{
rating: 10,
writer: "두근반 세근반",
movie_id: "5a54c286e8a71d136fb5378e",
contents:"정말 다섯 번은 넘게 운듯 ᅲᅲᅲ 감동 쩔어요.꼭 보셈 두 번 보셈"
}

이를 위해서는 먼저 위의 형태에 맞는 Codable struct를 만들어주어야 한다.

나는 다음과 같이 하였다:



import Foundation

struct PostComment: Codable {
    let movieId: String
    let rating: Double
    let writer: String
    let contents: String

    enum CodingKeys: String, CodingKey {
        case rating, writer, contents
        case movieId = "movie_id"
    }
}

그리고 본격적으로 post는 다음과 같이 수행하였다.

post 코드를 작성할 때에는 먼저 post할 body부분을 먼저 작성하고, 그 body를 JSONEncoder()로 encode 시킨 뒤
URLSession.uploadTask(with: request, from: encodedBody) 로 마무리한다.

구체적인 코드는 아래와 같으며, request.setvalue나 addvalue는 요구되는 header별로 달라질 수 있음에 유의하자.



func postComment(movieId: String, rating: Double, writer: String, contents: String) {

    // 넣는 순서도 순서대로여야 하는 것 같다.
    let comment = PostComment(movieId: movieId, rating: rating, writer: writer, contents: contents)
    guard let uploadData = try? JSONEncoder().encode(comment)
    else {return}

    // URL 객체 정의
    let url = URL(string: "https://connect-boxoffice.run.goorm.io/comment")

    // URLRequest 객체를 정의
    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    // HTTP 메시지 헤더
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    // URLSession 객체를 통해 전송, 응답값 처리
    let task = URLSession.shared.uploadTask(with: request, from: uploadData) { (data, response, error) in

        // 서버가 응답이 없거나 통신이 실패
        if let e = error {
            NSLog("An error has occured: \(e.localizedDescription)")
            return
        }
        // 응답 처리 로직
        print("comment post success")
    }
    // POST 전송
    task.resume()
}
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기
// custom