NetworkManager.swift 6.22 KB
Newer Older
domenicw's avatar
domenicw committed
1
2
3
4
5
6
7
8
9
10
//
//  NetworkManager.swift
//  Amiv
//
//  Created by Domenic Wüthrich on 23.09.18.
//  Copyright © 2018 Amiv an der ETH. All rights reserved.
//

import Foundation

11
public struct NetworkManager<EndPoint: EndPointType> {
domenicw's avatar
domenicw committed
12
    
13
    private let router = Router<EndPoint>()
domenicw's avatar
domenicw committed
14
15
16
17
18
    
    public enum NetworkResponse: String {
        case success
        case authenticationError = "You are not logged in."
        case badRequest = "Bad request"
19
        case failed = "Request failed"
domenicw's avatar
domenicw committed
20
21
22
23
24
        case noData = "Request was without data to decode."
        case unableToDecode = "Unable to decode data."
        case serverError = "Something went wrong at the AMIV server."
    }
    
domenicw's avatar
domenicw committed
25
    public enum RequestResult<String> {
domenicw's avatar
domenicw committed
26
27
28
29
        case success
        case failure(String)
    }
    
domenicw's avatar
domenicw committed
30
    fileprivate func handleNetworkRequest(_ response: HTTPURLResponse) -> RequestResult<String> {
domenicw's avatar
domenicw committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
        switch response.statusCode {
        case 200...299:
            return .success
        case 400:
            return .failure(NetworkResponse.badRequest.rawValue)
        case 401:
            return .failure(NetworkResponse.authenticationError.rawValue)
        case 404:
            return .failure(NetworkResponse.noData.rawValue)
        case 500:
            return .failure(NetworkResponse.serverError.rawValue)
        default:
            return .failure(NetworkResponse.failed.rawValue)
        }
    }
    
}

49
extension NetworkManager where EndPoint == AMIVApiEvents {
domenicw's avatar
domenicw committed
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
    
    public func getEvents(_ completion: @escaping (_ events: EventsResponse?, _ error: String?) -> Void) {
        router.request(.events) { (data, response, error) in
            guard error == nil else {
                completion(nil, "Please check your network connection.")
                return
            }
            
            if let response = response as? HTTPURLResponse {
                let result = self.handleNetworkRequest(response)
                switch result {
                case .success:
                    guard let responseData = data else {
                        completion(nil, NetworkResponse.noData.rawValue)
                        return
                    }
                    do {
                        let apiResponse = try JSONDecoder().decode(EventsResponse.self, from: responseData)
                        completion(apiResponse, nil)
                    } catch {
                        completion(nil, NetworkResponse.unableToDecode.rawValue)
                    }
                case .failure(let error):
                    completion(nil, error)
                }
            }
        }
    }
    
}
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178

extension NetworkManager where EndPoint == AMIVApiJobs {
    
    public func getJobOffers(_ completion: @escaping (_ response: [JobOffer]?, _ error: String?) -> Void) {
        router.request(.jobs) { (data, response, error) in
            guard error == nil else {
                completion(nil, error?.localizedDescription)
                return
            }
            
            guard let response = response as? HTTPURLResponse else {
                return
            }
            let result = self.handleNetworkRequest(response)
            switch result {
            case .success:
                guard let responseData = data else {
                    completion(nil, NetworkResponse.noData.rawValue)
                    return
                }
                do {
                    let apiResponse = try JSONDecoder().decode(JobsResponse.self, from: responseData)
                    completion(apiResponse._items, nil)
                } catch {
                    completion(nil, NetworkResponse.unableToDecode.rawValue)
                }
            case .failure(let error):
                completion(nil, error)
            }
        }
    }
    
}

extension NetworkManager where EndPoint == AMIVApiStudyDocuments {
    
    public func getStudyDocuments(_ completion: @escaping (_ response: [StudyDocument]?, _ error: String?) -> Void) {
        router.request(.overview) { (data, response, error) in
            guard error == nil else {
                completion(nil, error?.localizedDescription)
                return
            }
            
            guard let response = response as? HTTPURLResponse else {
                return
            }
            
            let result = self.handleNetworkRequest(response)
            switch result {
            case .success:
                guard let responseData = data else {
                    completion(nil, NetworkResponse.noData.rawValue)
                    return
                }
                do {
                    let apiResponse = try JSONDecoder().decode(StudyDocumentResponse.self, from: responseData)
                    completion(apiResponse._items, nil)
                } catch {
                    completion(nil, NetworkResponse.unableToDecode.rawValue)
                }
            case .failure(let error):
                completion(nil, error)
            }
        }
    }
    
}

extension NetworkManager where EndPoint == AMIVApiSession {
    
    public func authenticate(username: String, password: String, _ completion: @escaping (_ response: AuthenticationResponse?, _ error: String?) -> Void) {
        router.request(.authenticate(username: username, password: password)) { (data, response, error) in
            guard error == nil else {
                completion(nil, "Please check your network connection.")
                return
            }
            
            if let response = response as? HTTPURLResponse {
                let result = self.handleNetworkRequest(response)
                switch result {
                case .success:
                    guard let responseData = data else {
                        completion(nil, NetworkResponse.noData.rawValue)
                        return
                    }
                    do {
                        let apiResponse = try JSONDecoder().decode(AuthenticationResponse.self, from: responseData)
                        completion(apiResponse, nil)
                    } catch {
                        completion(nil, NetworkResponse.unableToDecode.rawValue)
                    }
                case .failure(let error):
                    completion(nil, error)
                }
            }
        }
    }
    
}