Last active
September 29, 2019 12:18
-
-
Save PetreVane/e7c16e571e32063a59ac72676dd51f4c to your computer and use it in GitHub Desktop.
This snipped shows a well structured example of a Networking Class, used in makeing request to a Weather API server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
enum DataManagerError: Error { | |
case Unknown | |
case FailedRequest | |
case InvalidResponse | |
} | |
final class DataManager { | |
typealias WeatherDataCompletion = (Location?, DataManagerError?) -> () | |
private let baseURL: URL | |
// MARK: - Initialization | |
init(baseURL: URL) { | |
self.baseURL = baseURL | |
} | |
// MARK: - Requesting Data | |
func weatherDataForLocation(latitude: Double, longitude: Double, completion: @escaping WeatherDataCompletion) { | |
// Create URL | |
let URL = baseURL.appendingPathComponent("\(latitude),\(longitude)") | |
// Create Data Task | |
URLSession.shared.dataTask(with: URL) { (data, response, error) in | |
self.didFetchWeatherData(data: data, response: response, error: error, completion: completion) | |
}.resume() | |
} | |
// MARK: - Helper Methods | |
private func didFetchWeatherData(data: Data?, response: URLResponse?, error: Error?, completion: WeatherDataCompletion) { | |
if let _ = error { | |
completion(nil, .FailedRequest) | |
} else if let data = data, let response = response as? HTTPURLResponse { | |
if response.statusCode == 200 { | |
processWeatherData(data: data, completion: completion) | |
} else { | |
completion(nil, .FailedRequest) | |
} | |
} else { | |
completion(nil, .Unknown) | |
} | |
} | |
private func processWeatherData(data: Data, completion: WeatherDataCompletion) { | |
if let JSON = try? JSONSerialization.jsonObject(with: data, options: []) { | |
completion(Location(JSON: JSON), nil) | |
} else { | |
completion(nil, .InvalidResponse) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment