Skip to content

Instantly share code, notes, and snippets.

@gbrigens
Created January 5, 2020 22:25
Show Gist options
  • Save gbrigens/71e29f2a40178870188500dc3d023c7d to your computer and use it in GitHub Desktop.
Save gbrigens/71e29f2a40178870188500dc3d023c7d to your computer and use it in GitHub Desktop.
Swift5 Result Type
struct HolidayResponse: Codable {
let response: Holidays
}
struct Holidays: Codable {
let holidays: [HolidayDetail]
}
struct HolidayDetail:Codable {
let name: String
let date: HolidayDate
}
struct HolidayDate: Codable {
let iso : String
}
enum HolidayError: Error {
case noDataAvailable
case canNotProcessData
}
struct HolidayRequest {
let resourceURL: URL
let API_KEY = "YOUR_API_KEY"
init(countryCode:String) {
let date = Date()
let format = DateFormatter()
format.dateFormat = "yyyy"
let currentYear = format.string(from: date)
let resourceString = "https://calendarific.com/api/v2/holidays?api_key=\(API_KEY)&country=\(countryCode)&year=\(currentYear)"
guard let resourceURL = URL(string: resourceString) else {
fatalError()
}
self.resourceURL = resourceURL
}
func getHolidays(completion: @escaping(Result<[HolidayDetail],HolidayError>) -> Void) {
let dataTask = URLSession.shared.dataTask(with: resourceURL) { (data, _, _) in
guard let jsonData = data else {
completion(.failure(.noDataAvailable))
return
}
do {
let decoder = JSONDecoder()
let holidayResponse = try decoder.decode(HolidayResponse.self, from: jsonData)
print("Holiday Res: \(holidayResponse)")
let holidayDetails = holidayResponse.response.holidays
completion(.success(holidayDetails))
}
catch {
completion(.failure(.canNotProcessData))
}
}
dataTask.resume()
}
}
func startRestApi(){
let holidayRequest = HolidayRequest(countryCode: "RU")
holidayRequest.getHolidays { (result) in
print(result)
}
holidayRequest.getHolidays { [weak self] result in
switch result {
case .failure(let error):
print(error)
case .success(let holidays):
self?.holidayArray = holidays
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment