NetworkManager.swift 12.6 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
    
    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)
                }
            }
        }
    }
    
domenicw's avatar
domenicw committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    public func getImage(for path: String, _ completion: @escaping (_ image: Data?, _ error: String?) -> Void) {
        router.request(.media(path)) { (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
                }
                completion(responseData, nil)
            case .failure(let error):
                completion(nil, error)
            }
        }
    }
    
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
    public func getEventSignups(_ completion: @escaping (_ image: Data?, _ error: String?) -> Void) {
        router.request(.eventSignups) { (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
                }
                completion(responseData, nil)
            case .failure(let error):
                completion(nil, error)
            }
        }
    }
    
domenicw's avatar
domenicw committed
128
}
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149

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 {
domenicw's avatar
domenicw committed
150
151
                    let apiResponse = try JSONDecoder().decode(JobOffersResponse.self, from: responseData)
                    completion(apiResponse.jobs, nil)
152
153
154
155
156
157
158
159
160
                } catch {
                    completion(nil, NetworkResponse.unableToDecode.rawValue)
                }
            case .failure(let error):
                completion(nil, error)
            }
        }
    }
    
domenicw's avatar
domenicw committed
161
162
    public func getMedia(for path: String, named: String, _ completion: @escaping (_ url: URL?, _ error: String?) -> Void) {
        router.download(.media(path), named) { (url, response, error) in
domenicw's avatar
domenicw committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
            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 url = url else {
                    completion(nil, NetworkResponse.noData.rawValue)
                    return
                }
                completion(url, nil)
            case .failure(let error):
                completion(nil, error)
            }
        }
    }
    
    public func getImage(for path: String, _ completion: @escaping (_ image: Data?, _ error: String?) -> Void) {
        router.request(.media(path)) { (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
                }
                completion(responseData, nil)
            case .failure(let error):
                completion(nil, error)
            }
        }
    }
    
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
}

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)
                }
            }
        }
    }
    
domenicw's avatar
domenicw committed
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
    public func logout(_ completion: @escaping (_ success: Bool, _ error: String?) -> Void) {
        router.request(.logout) { (data, response, error) in
            guard error == nil else {
                completion(false, "Please check your network connection.")
                return
            }
            
            if let response = response as? HTTPURLResponse {
                let result = self.handleNetworkRequest(response)
                switch result {
                case .success:
                    completion(true, nil)
                case .failure(let error):
                    completion(false, error)
                }
            }
        }
    }
    
}

extension NetworkManager where EndPoint == AMIVApiUser {
    
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
    public func getAllUsers(_ completion: @escaping (_ response: [User]?, _ error: String?) -> Void) {
        router.request(.allUsers) { (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(UsersResponse.self, from: responseData)
                        completion(apiResponse.users, nil)
                    } catch {
                        completion(nil, NetworkResponse.unableToDecode.rawValue)
                    }
                case .failure(let error):
                    completion(nil, error)
                }
            }
        }
    }
    
    public func getUserInfo(_ completion: @escaping (_ response: User?, _ error: String?) -> Void) {
domenicw's avatar
domenicw committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
        router.request(.userInfo) { (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(User.self, from: responseData)
                        completion(apiResponse, nil)
                    } catch {
                        completion(nil, NetworkResponse.unableToDecode.rawValue)
                    }
                case .failure(let error):
                    completion(nil, error)
                }
            }
        }
    }
    
354
}