APIManager.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //
  2. // APIManager.swift
  3. // LiveLikeGiphyChallenge
  4. //
  5. // Created by Arbnor Tefiki on 6.2.22.
  6. //
  7. import Foundation
  8. class APIManager {
  9. private static let giphyApiKey = "krF6wnSax3bZYT1kAAEfLeB1UwN7ZsJM"
  10. typealias GiphyResponse = (_ response: GiphyModel?) -> Void
  11. static func fetchTrendingGifs(request: GiphyRequest, completion: @escaping GiphyResponse) {
  12. var request = URLRequest(url: urlBuilder(request: request))
  13. request.httpMethod = "GET"
  14. URLSession.shared.dataTask(with: request) { (data, response, error) in
  15. if let err = error {
  16. print("Error fetching from Giphy: ", err.localizedDescription)
  17. completion(nil)
  18. }
  19. do {
  20. DispatchQueue.main.async {
  21. guard let data = data else {
  22. completion(nil)
  23. return
  24. }
  25. let object = try? JSONDecoder().decode(GiphyModel.self, from: data)
  26. completion(object)
  27. }
  28. }
  29. }.resume()
  30. }
  31. static func urlBuilder(request: GiphyRequest) -> URL {
  32. var components = URLComponents()
  33. components.scheme = "https"
  34. components.host = "api.giphy.com"
  35. components.path = "/v1/gifs/\(request.urlPath)"
  36. components.queryItems = [
  37. URLQueryItem(name: "api_key", value: giphyApiKey),
  38. URLQueryItem(name: "q", value: request.searchTerm),
  39. URLQueryItem(name: "limit", value: String(request.limit)),
  40. URLQueryItem(name: "offset", value: String(request.offset))
  41. ]
  42. return components.url!
  43. }
  44. }