Tom Coomer
Tom Coomer

Reputation: 6547

Firebase Download Task Queue Swift

I am currently downloading image files from Firebase Storage with the code below for the thumbnails in a UICollectionView.When I tap on one of the thumbnails, the app segues to another UIViewController that then downloads more images from Firebase Storage. Currently the app waits for all of the thumbnails to finish downloading before downloading the next images in the UIViewController. Is it possible to increase the priority of the new images in the UIViewController or cancel all other downloads to start the new ones immediately?

var imageRef = storageRef.child("Thumbnails/\(itemID).jpg")
imageRef.getData(maxSize: 10 * 1024 * 1024) { data, error 
    if let error = error {
        // Uh-oh, an error occurred!
        print("Error: \(error.localizedDescription)")
     } else {
        let image = UIImage(data: data!)
        self.newsNameArray.append(name)
        self.newsImageArray.append(image!)
        self.newsBarCollectionView?.reloadData()                        
      }
}

Thank you

Upvotes: 1

Views: 626

Answers (1)

leppen
leppen

Reputation: 176

You can get a reference to a StorageDownloadTask like this:

var allTasks: [StorageDownloadTask] = []

var imageRef = storageRef.child("Thumbnails/\(itemID).jpg")
let downloadTask = imageRef.getData(maxSize: 10 * 1024 * 1024) { data, error 
    if let error = error {
        // Uh-oh, an error occurred!
        print("Error: \(error.localizedDescription)")
     } else {
        let image = UIImage(data: data!)
        self.newsNameArray.append(name)
        self.newsImageArray.append(image!)
        self.newsBarCollectionView?.reloadData()                        
      }
}

Store your downloadTasks in an array and cancel all tasks before downloading the new images:

allTasks.append(downloadTask)

...

for task in allTasks {
    task.cancel()
}

Upvotes: 1

Related Questions