-
Notifications
You must be signed in to change notification settings - Fork 1
/
ApiManager.swift
107 lines (87 loc) · 3.54 KB
/
ApiManager.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
//
// ApiManager.swift
// A simple API call procedure
// 2019, Francesco Sorrentino
// https://it.linkedin.com/in/franksorro
import Foundation
class ApiManager: NSObject {
private override init() {}
public static let shared = ApiManager()
typealias CompletionHandler<T> = (Result<T>) -> ()
enum ApiError: Error {
case networkError(Error)
case dataNotFound
case jsonParsingError(Error)
case invalidStatusCode(Error)
case invalidParameters(Error)
case badUrl
}
enum Result<T> {
case success(T)
case failure(ApiError)
}
enum HttpMethods: String {
case get
case post
case put
case delete
}
enum Encoding {
case json
case data
case string
}
private let cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy
private let timeoutInterval: TimeInterval = 20.0
func request<T: Decodable>(with url: String,
type: T.Type,
_ method: HttpMethods = .get,
_ headers: [String: String] = [:],
_ parameters: Any? = nil,
_ encoding: Encoding = .json,
completion: @escaping CompletionHandler<T>) {
guard
let url = URL(string: url)
else {
completion(.failure(.badUrl))
return
}
var request = URLRequest(url: url,
cachePolicy: cachePolicy,
timeoutInterval: timeoutInterval)
request.httpMethod = method.rawValue
if let parameters = parameters {
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters,
options: [])
} catch let error {
completion(.failure(.invalidParameters(error)))
return
}
}
headers.forEach({ (key, value) in
request.addValue(value, forHTTPHeaderField: key)
})
URLSession.shared.dataTask(with: request,
completionHandler: { data, response, error in
guard
error == nil
else {
completion(.failure(.networkError(error!)))
return
}
guard
let data = data
else {
completion(.failure(.dataNotFound))
return
}
do {
let decodedObject = try JSONDecoder().decode(type, from: data)
completion(.success(decodedObject))
} catch let error {
completion(.failure(.jsonParsingError(error)))
}
}).resume()
}
}