-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataManager.swift
98 lines (79 loc) · 3.31 KB
/
DataManager.swift
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//
// DataManager.swift
// Beloe Radio
//
// Created by Danila Chub on 5/1/21.
// Copyright (c) 2020 Beloe-Radio.by. All rights reserved.
//
import UIKit
struct DataManager {
//*****************************************************************
// Helper struct to get either local or remote JSON
//*****************************************************************
static func getStationDataWithSuccess(success: @escaping ((_ metaData: Data?) -> Void)) {
DispatchQueue.global(qos: .userInitiated).async {
if useLocalStations {
getDataFromFileWithSuccess() { data in
success(data)
}
} else {
guard let stationDataURL = URL(string: stationDataURL) else {
if kDebugLog { print("stationDataURL not a valid URL") }
success(nil)
return
}
loadDataFromURL(url: stationDataURL) { data, error in
success(data)
}
}
}
}
//*****************************************************************
// Load local JSON Data
//*****************************************************************
static func getDataFromFileWithSuccess(success: (_ data: Data?) -> Void) {
guard let filePathURL = Bundle.main.url(forResource: "stations", withExtension: "json") else {
if kDebugLog { print("The local JSON file could not be found") }
success(nil)
return
}
do {
let data = try Data(contentsOf: filePathURL, options: .uncached)
success(data)
} catch {
fatalError()
}
}
//*****************************************************************
// REUSABLE DATA/API CALL METHOD
//*****************************************************************
static func loadDataFromURL(url: URL, completion: @escaping (_ data: Data?, _ error: Error?) -> Void) {
let sessionConfig = URLSessionConfiguration.default
sessionConfig.allowsCellularAccess = true
sessionConfig.timeoutIntervalForRequest = 15
sessionConfig.timeoutIntervalForResource = 30
sessionConfig.httpMaximumConnectionsPerHost = 1
let session = URLSession(configuration: sessionConfig)
// Use URLSession to get data from an NSURL
let loadDataTask = session.dataTask(with: url) { data, response, error in
guard error == nil else {
completion(nil, error!)
if kDebugLog { print("API ERROR: \(error!)") }
return
}
guard let httpResponse = response as? HTTPURLResponse, 200...299 ~= httpResponse.statusCode else {
completion(nil, nil)
if kDebugLog { print("API: HTTP status code has unexpected value") }
return
}
guard let data = data else {
completion(nil, nil)
if kDebugLog { print("API: No data received") }
return
}
// Success, return data
completion(data, nil)
}
loadDataTask.resume()
}
}