Kyrylo Kalashnikov
Kyrylo Kalashnikov

Reputation: 71

Loading screen while downloading images from Firebase

I have a bunch of images that i have to get from database with the following code where url is an array with link to images that are on Firebase storage.

func downloadFromServer(url: [String], imageNumber: Int){
    for i in url{
    let i = URL(string: i)
        print("I" , i)
        URLSession.shared.dataTask(with: i!) { data, response, error in
         guard
             let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
             let data = data, error == nil,
             let image = UIImage(data: data)

             else { return }
            print("Here", image)
         DispatchQueue.main.async() {
                print("Appended")
                imageArrayWatch.append(image)
                //imageArr.append(image)


         }
         }.resume()
    }

}

I want my app to display a loading screen while i am fetching images from the database. However, when i try to call showSpinner in my view controller like that

self.showSpinner(onView: self.view)
downloadFromServer(url: imageName)
self.removeSpinner()

Show and remove spinner function just show loading screen. This doesn't work because my downloadFromServer function exits before all images are fetched from the database and i see loading screen only for a second. How could i make my loading screen finish at the time when all of my images are appended to the mageArrayWatch array?

Upvotes: 0

Views: 221

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100533

You need a dispatch group

var imageArrayWatch = [UIImage]()

func downloadFromServer(url: [String], imageNumber: Int){
    let g = DispatchGroup()      ////// 1
    for i in url{
    let i = URL(string: i)
        print("I" , i)
        g.enter()         ////// 2
        URLSession.shared.dataTask(with: i!) { data, response, error in
         guard
             let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
             let data = data, error == nil,
             let image = UIImage(data: data)

            else {  g.leave() ;   return }   ////// 3
            print("Here", image)
         DispatchQueue.main.async() {
                print("Appended")
            self.imageArrayWatch.append(image)
            g.leave()    ////// 4
         }
         }.resume()
    }

    g.notify(queue: .main) {       ////// 5

        // stop loading here

    }
}

Upvotes: 3

Related Questions