Swift

[Swift] API 통신 URLSession / Alamofire

hyeonii_12 2020. 5. 28. 10:47
반응형

Swift에서 서버와 통신하기: URLSession / Alamofire

Swift Version 5
Xcode Version 11.5

URLSession

  • Body에 들어가는 파라미터가 한 개일 때
func sendMessage(chatContent: String) {
        let url = URL(string: "http://localhost:8080/test")
        var request = URLRequest(url: url!)

        request.httpMethod = "POST"

        // Header
        request.setValue("인증 정보", forHTTPHeaderField: "Authorization")

        // Body
        let data = "user_key=\(Bot.shared.access.appId)&content=\(chatText)".data(using: .utf8)

        request.httpBody = data

        URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let error = error {
                print("error: \(error.localizedDescription)")
                return
            }

            guard let data = String(bytes: data!, encoding: .utf8) else {
                return
            }

            print("data: \(data)")
        }.resume()
    }
  • Body에 들어가는 파라미터가 두 개 이상일 때
func sendMessage(chatContent: String) {
        let url = URL(string: "http://localhost:8080/test")
        var request = URLRequest(url: url!)

        request.httpMethod = "POST"

        // Header
        request.setValue("인증 정보", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        // Body
        let data = ["user_key": appId, "content": chatContent] as [String: Any]
        guard let jsonData = try? JSONSerialization.data(withJSONObject: data, options: []) else { return }

        request.httpBody = jsonData

        URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let error = error {
                print("error: \(error.localizedDescription)")
                return
            }

            guard let data = String(bytes: data!, encoding: .utf8) else {
                return
            }

            print("data: \(data)")
        }.resume()
    }

 

Alamofire

func sendMessage(chatContent: String) {
        let urlComponent = URLComponents(string: "http://localhost:8080/test")
        guard let url = urlComponent?.url else { return }

        // Header
        let header: HTTPHeaders = [
            "Authorization": "인증 정보"
        ]

        // Body
        let body = [
            "user_key": appId,
            "content": chatContent
            ] as [String: Any]

        let request = AF.request(url, method: .post, parameters: body, encoding: JSONEncoding.default, headers: header)
        request.validate(statusCode: 200...500).responseString { response in
            switch response.result {
            case .success:
                print(response.value)
            case .failure(let error):
                print(error)
            }
        }
}
반응형