Swift 3.0 으로 변하면서 NS라는 Prefix 명들이 모두 사라져서 깔끔해 진 느낌인데 여러가지로 API도 바뀌어서 매우 혼동이 됩니다.
그래서 특히 많이 사용하는 HTTP request를 정리해 보았습니다.
import Foundation
class Request {
let session: URLSession = URLSession.shared
// GET METHOD
func get(url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
var request: URLRequest = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
session.dataTask(with: request, completionHandler: completionHandler).resume()
}
// POST METHOD
func post(url: URL, body: NSMutableDictionary, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) throws {
var request: URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = try JSONSerialization.data(withJSONObject: body, options: JSONSerialization.WritingOptions.prettyPrinted)
session.dataTask(with: request, completionHandler: completionHandler).resume()
}
// PUT METHOD
func put(url: URL, body: NSMutableDictionary, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) throws {
var request: URLRequest = URLRequest(url: url)
request.httpMethod = "PUT"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = try JSONSerialization.data(withJSONObject: body, options: JSONSerialization.WritingOptions.prettyPrinted)
session.dataTask(with: request, completionHandler: completionHandler).resume()
}
// PATCH METHOD
func patch(url: URL, body: NSMutableDictionary, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) throws {
var request: URLRequest = URLRequest(url: url)
request.httpMethod = "PATCH"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = try JSONSerialization.data(withJSONObject: body, options: JSONSerialization.WritingOptions.prettyPrinted)
session.dataTask(with: request, completionHandler: completionHandler).resume()
}
// DELETE METHOD
func delete(url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
var request: URLRequest = URLRequest(url: url)
request.httpMethod = "DELETE"
request.addValue("application/json", forHTTPHeaderField: "Accept")
session.dataTask(with: request, completionHandler: completionHandler).resume()
}
}
사용예
let request: Request = Request()
let url: URL = URL(string: "https://api.example.com/path/to/resource")!
let body: NSMutableDictionary = NSMutableDictionary()
body.setValue("value", forKey: "key")
try request.post(url: url, body: body, completionHandler: { data, response, error in
// code
})