-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkingManager.swift
More file actions
66 lines (55 loc) · 2.08 KB
/
NetworkingManager.swift
File metadata and controls
66 lines (55 loc) · 2.08 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
56
57
58
59
60
61
62
63
64
65
66
//
// NetworkingManager.swift
// DefualtSource
//
// Created by xqsadness on 14/11/2023.
//
import Foundation
import Combine
/// The `NetworkingManager` class facilitates network-related operations, providing methods to download data from a specified URL. It is designed to handle asynchronous tasks using the Combine framework, offering a streamlined approach to network activities.
class NetworkingManager{
enum NetworkingError: LocalizedError{
case badURLResponse(url: URL)
case unowned
var errorDescription: String?{
switch self{
case .badURLResponse(url: let url): return "Bad response from url: \(url)"
case .unowned: return "unowned error occured"
}
}
}
static func download(url: URL) -> AnyPublisher<Data,Error>{
return URLSession.shared.dataTaskPublisher(for: url)
.subscribe(on: DispatchQueue.global(qos: .default))
.tryMap({ try handleURLResponse(output: $0, url: url) })
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
static func handleURLResponse(output: URLSession.DataTaskPublisher.Output, url: URL) throws -> Data{
guard let response = output.response as? HTTPURLResponse,
response.statusCode >= 200 && response.statusCode < 300 else{
throw NetworkingError.badURLResponse(url: url)
}
return output.data
}
static func handleCompeltion(completion: Subscribers.Completion<Error>){
switch completion{
case .finished:
break
case .failure(let err):
print(err.localizedDescription)
}
}
}
/*
-- Example
private func getDerivatives(){
guard let url = URL(string: API.instance.apiDerivatives) else {return}
NetworkingManager.download(url: url)
.decode(type: [DerivativesModel].self, decoder: JSONDecoder())
.sink(receiveCompletion: NetworkingManager.handleCompeltion) {[weak self] returnedDerivatives in
self?.dataDerivatives = returnedDerivatives
}
.store(in: &cancellables)
}
*/