-
Notifications
You must be signed in to change notification settings - Fork 5
/
Api+DataTask.swift
250 lines (207 loc) · 9.42 KB
/
Api+DataTask.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
public struct Constants{
typealias serviceCompletion = (_ data:Data?,_ response: URLResponse?,_ err: Error?) -> Void
static var baseUrl: String { ............ }
}
extension Data {
var prettyJson: String? {
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = String(data: data, encoding:.utf8) else { return nil }
return prettyPrintedString
}
}
/*
func getStudensListsAPI(isPage:Int, handler: @escaping Constants.serviceCompletion){
let url = "\(Constants.baseUrl)/get-students/\(Constants.activeUser?.userID ?? 0)/\(isPage)"
let request = DataTaskHandler()
request.handler = handler
request.fetchAsyncData(urlPath: url, dataToServer: Data(), params: [:], method: "GET")
}
func exapmle3PostAPI(updateProfileRequestBody:UpdateProfileResponseRequest,_ handler:@escaping Constants.serviceCompletion){
let request = DataTaskHandler()
request.handler = handler
guard let data = try? JSONEncoder().encode(updateProfileRequestBody) else { return }
request.fetchAsyncData(urlPath: "\(Constants.baseUrl)/update-profile", dataToServer:data, params: [:], method: "POST")
}
*/
import Foundation
class DataTaskHandler {
var handler : Constants.serviceCompletion?
var urlpath:URL?
var request:URLRequest?
func fetchAsyncData(urlPath : String, dataToServer : Data, params:Dictionary<String, Any> , method: String = "GET", isPublic:Bool = false,header:[String:String] = StringDictionary())
{
var headerDict = header
request = URLRequest(url: URL(string: urlPath)!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60.0)
request?.httpMethod = method
// if !isPublic{
// headerDict["TOKEN"] = Constants.token
// headerDict["OS"] = "ios"
// }
// headerDict["PACKAGE"] = Constants.packageName
request?.setValue("application/json", forHTTPHeaderField: "Content-Type")
switch method {
case "GET":
if !params.isEmpty {
var urlComp = URLComponents(string: urlPath)!
var items = [URLQueryItem]()
for (key,value) in params {
items.append(URLQueryItem(name: key, value: value as? String))
}
items = items.filter{!$0.name.isEmpty}
if !items.isEmpty {
urlComp.queryItems = items
}
urlpath = urlComp.url
request?.url = urlpath
}
case "POST", "PUT":
request?.httpBody = dataToServer
default:
break
}
request?.allHTTPHeaderFields = headerDict
debugPrint("URL \(urlPath)")
debugPrint("Token \(Constants.token)")
debugPrint("Headers \(request?.allHTTPHeaderFields?.description ?? "No Header")")
if let debugData = request?.httpBody{
debugPrint("Request Body \(debugData.prettyJson ?? "No Body")")
}
let configuration = URLSessionConfiguration.default
let task = URLSession(configuration: configuration).dataTask(with: request!) { (data, response, error) in
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.statusCode,"<--------CODE")
}
DispatchQueue.main.async {
self.handler?(data, response, error)
}
if let debugData = data{
debugPrint("Response Body \(debugData.prettyJson ?? "No Body")")
}
}
task.resume()
}
}
extension DataTaskHandler
{
func fetchAsyncFormData(urlPath : String, dataToServer : Data, params:Dictionary<String, Any> , method: String = "GET", isPublic:Bool = false,header:[String:String] = StringDictionary()){
var headerDict = header
request = URLRequest(url: URL(string: urlPath)!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60.0)
request?.httpMethod = method
if !isPublic{
headerDict["TOKEN"] = Constants.token
headerDict["OS"] = "ios"
}
headerDict["PACKAGE"] = Constants.packageName
let boundary = "Boundary-\(UUID().uuidString)"
request?.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
switch method {
case "GET":
if !params.isEmpty {
var urlComp = URLComponents(string: urlPath)!
var items = [URLQueryItem]()
for (key,value) in params {
items.append(URLQueryItem(name: key, value: value as? String))
}
items = items.filter{!$0.name.isEmpty}
if !items.isEmpty {
urlComp.queryItems = items
}
urlpath = urlComp.url
request?.url = urlpath
}
case "POST", "PUT":
request?.httpBody = createBodyWithParameters(param: params as? [String : String], boundary: boundary)
default:
break
}
debugPrint("URL \(urlPath)")
debugPrint("Token \(Constants.token)")
debugPrint("Headers \(request?.allHTTPHeaderFields?.description ?? "No Header")")
debugPrint("Params Request Body: \(params)")
request?.allHTTPHeaderFields = headerDict
let configuration = URLSessionConfiguration.default
let task = URLSession(configuration: configuration).dataTask(with: request!) { (data, response, error) in
DispatchQueue.main.async {
self.handler?(data, response, error)
}
if let debugData = data{
debugPrint("Response Body \(debugData.prettyJson ?? "No Body")")
}
}
task.resume()
}
func createBodyWithParameters(param:[String:String]?, boundary: String) -> Data {
var body = Data()
if(param != nil) {
for (key,value) in param! {
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
return body
}
}
extension DataTaskHandler{
func fetchAsyncUrlEncodedDataFormUrl(urlPath : String, queryParams : Dictionary<String, String> , headerParams:Dictionary<String, Any> , method: String = "GET", isPublic:Bool = false,header:[String:String] = StringDictionary()){
var headerDict = header
request = URLRequest(url: URL(string: urlPath)!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60.0)
request?.httpMethod = method
if !isPublic{
headerDict["TOKEN"] = Constants.token
headerDict["OS"] = "ios"
}
headerDict["PACKAGE"] = Constants.packageName
switch method {
case "GET":
if !headerParams.isEmpty {
var urlComp = URLComponents(string: urlPath)!
var items = [URLQueryItem]()
for (key,value) in headerParams {
items.append(URLQueryItem(name: key, value: value as? String))
}
items = items.filter{!$0.name.isEmpty}
if !items.isEmpty {
urlComp.queryItems = items
}
urlpath = urlComp.url
request?.url = urlpath
}
case "POST", "PUT":
request?.httpMethod = "POST";
request?.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request?.httpBody = createFormUrlEncodedData(params: queryParams)
default:
break
}
request?.allHTTPHeaderFields = headerDict
debugPrint("URL \(urlPath)")
debugPrint("Token \(Constants.token)")
debugPrint("Headers \(request?.allHTTPHeaderFields?.description ?? "No Header")")
if let debugData = request?.httpBody{
debugPrint("Request Body \(debugData.prettyJson ?? "No Body")")
}
let configuration = URLSessionConfiguration.default
let task = URLSession(configuration: configuration).dataTask(with: request!) { (data, response, error) in
DispatchQueue.main.async {
self.handler?(data, response, error)
}
if let debugData = data{
debugPrint("Response Body \(debugData.prettyJson ?? "No Body")")
}
}
task.resume()
}
func createFormUrlEncodedData(params:[String:String]) -> Data{
var requestComponent = URLComponents()
var data = [URLQueryItem]()
for (key,value) in params{
data.append(URLQueryItem(name: key, value: value))
}
requestComponent.queryItems = data
return requestComponent.query?.data(using: .utf8) ?? Data()
}
}