Home > Enterprise >  How to wait till download from Firebase Storage is completed before executing a completion swift
How to wait till download from Firebase Storage is completed before executing a completion swift

Time:03-02

In the below model that downloads the images from Firebase Storage it completes the for loop, but the print statement in the completion block shows "[]". However, moments later the downloads arrive & show in the array. How do I wait for the images to fully download & enter into the array before executing the completion & reload a table later?

View Model: Downloads Image


    //Firebase Cloud Storage Reference:
    let storage = Storage.storage()
    
    public var imageArray: [UIImage] = []

    public func fetchProductImages(completion: @escaping (Result<UIImage, Error>) -> Void) {
        
        //Clear Image Array:
        imageArray.removeAll()
        
        for imageRef in products! {
            
            //Access to Image inside a Collection:
            let storageRef = self.storage.reference(withPath: imageRef.image!)
            
            //Download in Memory with a Maximum Size of 1MB (1 * 1024 * 1024 Bytes):
            storageRef.getData(maxSize: 1 * 1024 * 1024) { [self] data, error in
                
                if let error = error {
                    //Error:
                    print (error)
                    
                } else {
                    
                    //Image Returned Successfully:
                    let image = UIImage(data: data!)

                    //Add Images to the Array:
                    imageArray.append(image!)
                    
                }
            }
        }
        
        print (imageArray)
        
        completion (true)
        
    }


CodePudding user response:

Since loading the image data is an asynchronous operation, any code that needs to run after the images have loaded will need to be inside the completion handler, be called from there, or be otherwise synchronized.

A simple way is to count the number of images that have completely loaded, and call once it matches the length of the array:

imageArray.removeAll()

for imageRef in products! {
    
    let storageRef = self.storage.reference(withPath: imageRef.image!)
    
    storageRef.getData(maxSize: 1 * 1024 * 1024) { [self] data, error in
        
        if let error = error {
            print (error)                
        } else {
            
            //Image Returned Successfully:
            let image = UIImage(data: data!)

            //Add Images to the Array:
            imageArray.append(image!)

            //            
  • Related