Skip to content

Instantly share code, notes, and snippets.

@yashthaker7
Last active May 29, 2020 17:11
Show Gist options
  • Save yashthaker7/acc754906181e1b169b23be59fb32299 to your computer and use it in GitHub Desktop.
Save yashthaker7/acc754906181e1b169b23be59fb32299 to your computer and use it in GitHub Desktop.
generic function for api service
// Service.swift
// Generics
//
// Created by Yash Thaker on 25/05/20.
// Copyright © 2020 YashThaker. All rights reserved.
//
/*
// ------------- How to use -------------
Service.shared.fetchUnsplashPhotos { result in
switch result {
case .failure(let error):
print("Error: ", error)
case .success(let unsplashResults):
print(unsplashResults)
}
}
*/
import UIKit
import Alamofire
protocol LocalizedDescriptionError: Error {
var localizedDescription: String { get }
}
final class Service {
static let shared = Service()
private init() { }
enum Result<Success, Failure: Error> {
case success(Success)
case failure(Failure)
}
enum ServiceError: LocalizedDescriptionError {
case canNotCastResponseData
var localizedDescription: String {
switch self {
case .canNotCastResponseData:
return "Can not cast response data."
}
}
}
func fetchUnsplashPhotos(currentPage: Int = 1, completion: @escaping (Result<[Unsplash_Results], Error>) -> ()) {
let urlString = "https://api.unsplash.com/photos/?"
var parameters = [String: Any]()
parameters["client_id"] = "a21c1d02e7f4850714142dc5664cb908af6568a31e9059562ca4b9b9a4a79f65"
parameters["per_page"] = 60
parameters["page"] = currentPage
fetchGenericData(urlString: urlString, parameters: parameters, completion: completion)
}
private func fetchGenericData<T: Decodable>(urlString: String, parameters: [String: Any]? = nil, completion: @escaping (Result<T, Error>) -> ()) {
AF.request(urlString, parameters: parameters).responseData { (response) in
if let error = response.error {
completion(.failure(error))
return
}
guard let data = response.data else {
completion(.failure(ServiceError.canNotCastResponseData))
return
}
do {
let model = try JSONDecoder().decode(T.self, from: data)
completion(.success(model))
} catch let jsonError {
completion(.failure(jsonError))
return
}
}
}
}
// MARK:- Unsplash
struct Unsplash_Results : Decodable {
let width : Int?
let height : Int?
let urls : Urls?
}
struct Urls : Decodable {
let regular : String?
let thumb : String?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment