@@ -12,9 +12,9 @@ public extension URLSession {
1212 public func errorMessage( ) -> String {
1313 switch self {
1414 case . invalidURL( let str) :
15- return " badURL : \( str) "
15+ return " bad URL : \( str) "
1616 case . networkError( let error) :
17- return " networkError : \( error) "
17+ return " network Error : \( error) "
1818 case . noResponse:
1919 return " no network response "
2020 case . decodingError( let error) :
@@ -26,17 +26,37 @@ public extension URLSession {
2626 enum HTTPMethod {
2727
2828 case get
29+ case post
30+ case put
31+ case delete
2932
3033 var id : String {
3134 switch self {
3235 case . get: return " get "
36+ case . post: return " post "
37+ case . put: return " put "
38+ case . delete : return " delete "
39+ }
40+ }
41+ }
42+
43+ enum ContentType {
44+
45+ case application_json
46+
47+ var id : String {
48+ switch self {
49+ case . application_json:
50+ " application/json "
3351 }
3452 }
3553 }
3654
3755 static func request(
3856 url: String ,
3957 method: HTTPMethod ,
58+ body: [ String : Any ] ? = nil ,
59+ contentTypeHeader: ContentType ? = nil ,
4060 completion: @escaping ( AppError ? , Data ? , HTTPURLResponse ? ) -> Void )
4161 {
4262 guard let url = URL ( string: url) else {
@@ -46,6 +66,24 @@ public extension URLSession {
4666
4767 var request = URLRequest ( url: url)
4868 request. httpMethod = method. id
69+
70+ // Content Type
71+ if let contentTypeHeader {
72+ request. setValue ( contentTypeHeader. id, forHTTPHeaderField: " Content-Type " )
73+ }
74+
75+ // Body
76+ if let body {
77+ do {
78+ let jsonData = try JSONSerialization . data ( withJSONObject: body, options: [ ] )
79+ request. httpBody = jsonData
80+ } catch {
81+ completion ( . decodingError( error) , nil , nil )
82+ return
83+ }
84+ }
85+
86+ // Make Request
4987 URLSession . shared. dataTask ( with: request) { ( data, response, error) in
5088 guard let response = response as? HTTPURLResponse else {
5189 completion ( AppError . noResponse, nil , nil )
0 commit comments