Midoxx
Midoxx

Reputation: 67

Swift UIImage Array from JSON URL

I try to create an Array of UIImages from a URL Array received from a JSON Request to show them afterwards in a UITableView. But somehow my UIImage Array stays Empty and is not receiving any Data. The other Arrays for example memeURL are receiving all Data correct but memePics.count stays on 0.

Would be great if someone could show me what i am doing wrong. Also if for this task there is a better way on how to do it - it would be also appreciated!

Var:

var memePics: [UIImage] = []

Loop to add Images to Array:

while(i < memeURL.count) {
            MemeAPI.requestAPIImageFile(url: memeURL[i]) { (image, error) in
                guard let image = image else {
                    print("PIC IS NIL")
                    return
                }
                self.memePics.append(image)
                i+=1
            }
        }

RequestAPIImageFile Function:

class func requestAPIImageFile(url: URL, completionHandler: @escaping (UIImage?, Error?) -> Void) {
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let data = data else {
                completionHandler(nil, error)
                return}
            let downloadedImage = UIImage(data: data)
            completionHandler(downloadedImage, nil)
        }
        task.resume()
    }

Upvotes: 0

Views: 149

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100523

Add plus line out of callback

  self.memePics.append(image)
  }
  i+=1

and use DispatchGroup to be notified on finish like

let g = DispatchGroup()
memeURL.forEach {  
        g.enter()
        MemeAPI.requestAPIImageFile(url:$0) { (image, error) in
            guard let image = image else {
                print("PIC IS NIL")
                return
            }
            self.memePics.append(image) 
            g.leave()
        }
} 
g.notify(queue:.main) {
   print("All done")
}

Upvotes: 1

Related Questions