-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathNetworManager.swift
More file actions
51 lines (41 loc) · 1.63 KB
/
NetworManager.swift
File metadata and controls
51 lines (41 loc) · 1.63 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
//
// NetworManager.swift
// GitHubApp
//
// Created by GISELE TOLEDO on 10/04/23.
//
import Foundation
protocol NetworkManagerProtocol {
func get<T: Decodable>(request: URLRequest, completion: @escaping (Result<T, Error>) -> Void)
}
final class NetworkManager: NetworkManagerProtocol {
private let session: URLSession
init(session: URLSession = .shared) {
self.session = session
}
func get<T: Decodable>(request: URLRequest, completion: @escaping (Result<T, Error>) -> Void) {
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data, let httpResponse = response as? HTTPURLResponse else {
completion(.failure(NSError(domain: "Invalid response", code: 0, userInfo: nil)))
return
}
guard (200...299).contains(httpResponse.statusCode) else {
let statusCode = httpResponse.statusCode
let localizedDescription = HTTPURLResponse.localizedString(forStatusCode: statusCode)
completion(.failure(NSError(domain: "HTTP Error", code: statusCode, userInfo: [NSLocalizedDescriptionKey: localizedDescription])))
return
}
do {
let decodedData = try JSONDecoder().decode(T.self, from: data)
completion(.success(decodedData))
} catch {
completion(.failure(error))
}
}
task.resume()
}
}