Advertisement
Guest User

Untitled

a guest
Oct 27th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. //
  2. // CarRequest.swift
  3. // Cats
  4. //
  5. // Created by Руслан on 26.10.2019.
  6. // Copyright © 2019 Руслан. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10. import UIKit
  11.  
  12. class CatRequest {
  13.  
  14. func getCat(url: String = "https://api.thecatapi.com/v1/images/search", completionSuccess: @escaping (UIImage) -> Void, completionError: @escaping (String) -> Void) {
  15. guard let url = URL(string: url) else {return}
  16. let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
  17. guard error == nil else {
  18. completionError(error?.localizedDescription ?? "Error connection")
  19. return
  20. }
  21.  
  22. guard let data = data,
  23. let jsonArray = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]],
  24. let json = jsonArray.first else {
  25. completionError("Nil data received")
  26. return
  27. }
  28.  
  29. guard let cat: Cat = Cat(json) else {
  30. completionError("Malformed data received")
  31. return
  32. }
  33.  
  34. self.downlandImage(url: cat.url, completion: { (image) in
  35. if let image = image {
  36. completionSuccess(image)
  37. } else {
  38. completionError("Nil data Image")
  39. }
  40. })
  41. }
  42. task.resume()
  43. }
  44.  
  45. func downlandImage(url: String, completion: @escaping (UIImage?) -> Void){
  46. guard let url = URL(string: url) else {
  47. completion(nil)
  48. return
  49. }
  50. let task = URLSession.shared.dataTask(with: url) { data, response, error in
  51. guard
  52. let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
  53. let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
  54. let data = data, error == nil,
  55. let image = UIImage(data: data)
  56. else {
  57. completion(nil)
  58. return
  59. }
  60. completion(image)
  61. }
  62. task.resume()
  63. }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement