HTTP 통신 구현
(Swift)Request Function - GET / DELETE
// Request Body 미포함
func httpRequestQuery(url: String, method: String, completionHandler: @escaping (Bool, Any) -> Void) {
guard let url = URL(string: url) else {
print("Error: cannot create URL")
return
}
var request = URLRequest(url: url)
request.httpMethod = method
URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print("Error: error calling GET")
print(error!)
return
}
guard let data = data else {
print("Error: Did not receive data")
return
}
guard let response = response as? HTTPURLResponse, (200..<300) ~= response.statusCode else {
print("Error: HTTP request failed")
return
}
guard let output = try? JSONDecoder().decode(Response.self, from: data) else {
print("Error: JSON Parsing Error")
return
}
completionHandler(true, output.result)
}.resume()
}
(Swift)Request Function - POST / PUT
// Request Body 포함
func httpRequestBody(url: String, method: String, param:[String: Any],completionHandler: @escaping (Bool, Any) -> Void) {
let sendData = try! JSONSerialization.data(withJSONObject: param, options: [])
guard let url = URL(string: url) else {
print("Error: cannot create URL")
return
}
var request = URLRequest(url: url)
request.httpMethod = method
// HTTP Request header
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// HTTP Request body
request.httpBody = sendData
URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print("Error: error calling POST")
print(error!)
return
}
guard let data = data else {
print("Error: Did not receive data")
return
}
guard let response = response as? HTTPURLResponse, (200..<300) ~= response.statusCode else {
print("Error: HTTP request failed")
return
}
guard let output = try? JSONDecoder().decode(Response.self, from: data) else {
print("Error: JSON Parsing Error")
return
}
completionHandler(true, output.result)
}.resume()
}
HTTP Request 호출 function
func request(_ url: String, _ method: String, _ param: [String: Any]? = nil, completionHandler: @escaping (Bool, Any) -> Void) {
if method == "GET" || method == "DELETE" {
httpRequestQuery(url: url, method: method) { success, data in
completionHandler(success, data)
}
}
else {
httpRequestBody(url: url, method: method, param: param!) { success, data in
completionHandler(success, data)
}
}
}
ViewController
class ViewController: UIViewController {
private let url = "http://127.0.0.1:3000/"
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func TappedGetButton(_ sender: UIButton) {
print("Get")
request(url, "GET") { success, data in
print(data)
}
}
@IBAction func TappedPostButton(_ sender: UIButton) {
print("Post")
request(url, "POST", ["Key": "Request Post", "Method": "POST"]) { success, data in
print(data)
}
}
@IBAction func TappedPutButton(_ sender: UIButton) {
print("Put")
request(url, "PUT", ["Key": "Request Put", "Method": "PUT"]) { success, data in
print(data)
}
}
@IBAction func TappedDeleteButton(_ sender: UIButton) {
print("Delete")
request(url, "DELETE") { success, data in
print(data)
}
}
}
테스트 결과