// // APIManager.swift // LiveLikeGiphyChallenge // // Created by Arbnor Tefiki on 6.2.22. // import Foundation class APIManager { private static let giphyApiKey = "krF6wnSax3bZYT1kAAEfLeB1UwN7ZsJM" typealias GiphyResponse = (_ response: GiphyModel?) -> Void static func fetchTrendingGifs(request: GiphyRequest, completion: @escaping GiphyResponse) { var request = URLRequest(url: urlBuilder(request: request)) request.httpMethod = "GET" URLSession.shared.dataTask(with: request) { (data, response, error) in if let err = error { print("Error fetching from Giphy: ", err.localizedDescription) completion(nil) } do { DispatchQueue.main.async { guard let data = data else { completion(nil) return } let object = try? JSONDecoder().decode(GiphyModel.self, from: data) completion(object) } } }.resume() } static func urlBuilder(request: GiphyRequest) -> URL { var components = URLComponents() components.scheme = "https" components.host = "api.giphy.com" components.path = "/v1/gifs/\(request.urlPath)" components.queryItems = [ URLQueryItem(name: "api_key", value: giphyApiKey), URLQueryItem(name: "q", value: request.searchTerm), URLQueryItem(name: "limit", value: String(request.limit)), URLQueryItem(name: "offset", value: String(request.offset)) ] return components.url! } }