@@ -12,9 +12,9 @@ public extension URLSession {
12
12
public func errorMessage( ) -> String {
13
13
switch self {
14
14
case . invalidURL( let str) :
15
- return " badURL : \( str) "
15
+ return " bad URL : \( str) "
16
16
case . networkError( let error) :
17
- return " networkError : \( error) "
17
+ return " network Error : \( error) "
18
18
case . noResponse:
19
19
return " no network response "
20
20
case . decodingError( let error) :
@@ -26,17 +26,37 @@ public extension URLSession {
26
26
enum HTTPMethod {
27
27
28
28
case get
29
+ case post
30
+ case put
31
+ case delete
29
32
30
33
var id : String {
31
34
switch self {
32
35
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 "
33
51
}
34
52
}
35
53
}
36
54
37
55
static func request(
38
56
url: String ,
39
57
method: HTTPMethod ,
58
+ body: [ String : Any ] ? = nil ,
59
+ contentTypeHeader: ContentType ? = nil ,
40
60
completion: @escaping ( AppError ? , Data ? , HTTPURLResponse ? ) -> Void )
41
61
{
42
62
guard let url = URL ( string: url) else {
@@ -46,6 +66,24 @@ public extension URLSession {
46
66
47
67
var request = URLRequest ( url: url)
48
68
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
49
87
URLSession . shared. dataTask ( with: request) { ( data, response, error) in
50
88
guard let response = response as? HTTPURLResponse else {
51
89
completion ( AppError . noResponse, nil , nil )
0 commit comments