Last active
October 2, 2018 01:16
-
-
Save richimf/311d72b8d686359b6eed9221193aea97 to your computer and use it in GitHub Desktop.
Protocol Oriented Programing [Networking-Error Example]
This file contains 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
/**** | |
Protocol Oriented Programing | |
Networking-Error Example | |
***/ | |
import Foundation | |
public protocol NetworkController { | |
func fetchCurrentWeatherData(city: String, | |
completionHandler: @escaping (WeatherData?, NetworkControllerError?) -> Void) -> WeatherData? | |
} | |
public struct WeatherData { | |
var temperature: Float | |
var condition: String | |
var unit: TemperatureUnit | |
} | |
public enum TemperatureUnit: String { | |
case scientific = "scientific" | |
case metric = "metric" | |
case imperial = "imperial" | |
} | |
public enum NetworkControllerError: Error { | |
case invalidURL(String) | |
case invalidPayload(URL) | |
case forwarded(Error) | |
} | |
/// IMPLEMENTATION | |
func fetchCurrentWeatherData(city: String, | |
completionHandler: @escaping (WeatherData?, NetworkControllerError?) -> Void) -> WeatherData? { | |
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main) | |
let endpoint = "http://URL/API" | |
let safeURLString = endpoint.addingPercentEncoding(withAllowedCharacters: .urlQueryallowed) | |
guard let endpointURL = URL(string: safeURLString!) else { | |
completionHandler(nil, NetworkControllerError.invalidURL(safeURLString!)) | |
return | |
} | |
let dataTask = session.dataTask(witch: endpointURL) { (data, response, error) in | |
guard error == nil else { | |
completionHandler(nil, NetworkControllerError.forwarded(error!)) | |
return | |
} | |
guard let jsonData = data else { | |
completionHandler(nil, NetworkControllerError.invalidPayload(endpointURL)) | |
} | |
self.decode(jsonDta: jsonData, endpointURL: URL, completionHandler: completionHandler) | |
}//end dataTask | |
dataTask.resume() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment