I'm trying to use Imgur API on a iOS app, but for some reason I can't get it to work right. I've managed to connect to the API, retrieve it's values and parse to my Decodable Model. In my ViewModel file, if I print the images completion, the console output the received data. But when I try to assign it to an array, where I can use it's values inside my ViewController, the returned array is always empty.
Any clues on what I'm missing here?
Thanks a lot!!
Model:
struct ImgurResponse: Decodable {
let data: [Image]
}
struct Image: Decodable {
let title: String
let link: String
}
Service:
struct Service {
func fetchImages(_ completion: @escaping ([Image]?) -> Void) {
guard let url = URL(string: "https://api.imgur.com/3/gallery/search/viral/?q=cats") else { return }
var request = URLRequest(url: url)
request.setValue("Client-ID -hidden-", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let dataTask = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
if let _ = error {
completion(nil)
return
}
if let data = data {
let jsonDecodable = JSONDecoder()
do {
let decode = try jsonDecodable.decode(ImgurResponse.self, from: data)
completion(decode.data)
} catch {
print(error)
completion(nil)
}
}
}
dataTask.resume()
}
}
ViewModel:
class ImageViewModel {
private let service = Service()
var images = [Image]()
func fetchImages() -> [Image] {
service.fetchImages { images in
guard let images = images else { return }
self.images = images
}
return images
}
}
ViewController:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.fetchImages().count
}