-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPI.swift
107 lines (75 loc) · 3.63 KB
/
API.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
//
// API.swift
// IOS2-MapKit
//
// Created by Alireza Gholami on 2022-02-19.
//
import Foundation
class API {
static func httpStatusCode( response : Any ) -> Int? {
if let httpResponse = response as? HTTPURLResponse {
return httpResponse.statusCode
} else {
return nil
}
}
static func call( baseURL : String,
endPoint : String,
method : String = "POST",
header : [String:String] = [:],
payload : [String:Any],
successHandler: @escaping (_ httpStatusCode : Int, _ response : [String: Any]) -> Void,
failHandler : @escaping (_ httpStatusCode : Int, _ errorMessage: String) -> Void) {
let Url = String(format: "\(baseURL)\(endPoint)")
guard let serviceUrl = URL(string: Url) else { return }
var httpStatusCode : Int = 0
var request = URLRequest(url: serviceUrl)
request.httpMethod = method.uppercased()
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
for (key, value) in header {
request.setValue(value, forHTTPHeaderField: key)
}
guard let httpBody = try? JSONSerialization.data(withJSONObject: payload, options: []) else {
failHandler(httpStatusCode, "Unknow data received from server.")
return
}
if payload.count > 0 {
request.httpBody = httpBody
}
let session = URLSession.shared.dataTask(with: request) {
(data, response, error) in
if error == nil && data != nil {
httpStatusCode = API.httpStatusCode( response : response! ) ?? 0
if let response = data {
do {
if let jsonObject = try JSONSerialization.jsonObject(with: response, options : []) as? [String : Any]{
print(jsonObject)
print("*** HTTP Response Code: \(httpStatusCode)")
if !(200..<300).contains(httpStatusCode) {
if let errorMessage : [String : Any] = jsonObject["error"] as? [String : Any] {
failHandler(httpStatusCode, errorMessage["message"] as! String)
} else {
failHandler(httpStatusCode, "Something went wrong! (http code: \(httpStatusCode))")
}
return
}
successHandler(httpStatusCode, jsonObject)
return
}
} catch {
failHandler(httpStatusCode, "Something went wrong when decoding server response!")
return
}
} else {
failHandler(httpStatusCode, "Unknow data received from the server!")
return
}
} else {
print(error!)
let errorMsg = "Fetch failed: \(error?.localizedDescription ?? "Unknown error")"
failHandler(httpStatusCode, errorMsg)
return
}
}.resume()
}
}