-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAPIManager.swift
More file actions
55 lines (41 loc) · 1.46 KB
/
APIManager.swift
File metadata and controls
55 lines (41 loc) · 1.46 KB
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
//
// APIManager.swift
// SimpleVIPExample
//
// Created by Vishal_Malvi on 12/02/23.
//
import Foundation
typealias RequestResult<T> = (Result<T, CustomErrors>) -> Void
final class APIManager {
static let shared = APIManager()
private init() {}
static var sharedHeaders : HTTPHeaders {
["Content-Type": "application/json"]
}
func request<T: Codable>(modelType: T.Type, type: EndPoint, completion: @escaping RequestResult<T>) {
guard let url = type.url else {
completion(.failure(.invalidURL))
return
}
var request = URLRequest(url: url)
request.httpMethod = type.method.rawValue
request.allHTTPHeaderFields = type.headers
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data, error == nil else {
completion(.failure(.invalidData))
return
}
guard let response = response as? HTTPURLResponse,
200 ... 299 ~= response.statusCode else {
completion(.failure(.invalidResponse))
return
}
do {
let model = try JSONDecoder().decode(modelType, from: data)
completion(.success(model))
}catch {
completion(.failure(.network(error)))
}
}.resume()
}
}