Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // CarRequest.swift
- // Cats
- //
- // Created by Руслан on 26.10.2019.
- // Copyright © 2019 Руслан. All rights reserved.
- //
- import Foundation
- import UIKit
- class CatRequest {
- func getCat(url: String = "https://api.thecatapi.com/v1/images/search", completionSuccess: @escaping (UIImage) -> Void, completionError: @escaping (String) -> Void) {
- guard let url = URL(string: url) else {return}
- let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
- guard error == nil else {
- completionError(error?.localizedDescription ?? "Error connection")
- return
- }
- guard let data = data,
- let jsonArray = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]],
- let json = jsonArray.first else {
- completionError("Nil data received")
- return
- }
- guard let cat: Cat = Cat(json) else {
- completionError("Malformed data received")
- return
- }
- self.downlandImage(url: cat.url, completion: { (image) in
- if let image = image {
- completionSuccess(image)
- } else {
- completionError("Nil data Image")
- }
- })
- }
- task.resume()
- }
- func downlandImage(url: String, completion: @escaping (UIImage?) -> Void){
- guard let url = URL(string: url) else {
- completion(nil)
- return
- }
- let task = URLSession.shared.dataTask(with: url) { data, response, error in
- guard
- let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
- let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
- let data = data, error == nil,
- let image = UIImage(data: data)
- else {
- completion(nil)
- return
- }
- completion(image)
- }
- task.resume()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement