Jiacai Lau Jiacai Lau - 7 months ago 74
Swift Question

Firebase Storage Async Image Download not in the right order

I am met with a problem when I tried to download a batch of images off firebase storage. Basically, because the file sizes differ, the images are not appended to the image array properly causing the images to be in the wrong order that I wanted. Below is the code

import Foundation
import FirebaseStorage

class GalleryCellDetailedData {

var selectedGallery:String?
var count:Int


self.selectedGallery = selectedGallery
self.count = count


func addImages(completion:(data:[NSData])->()){

var datas = [NSData]()

let myGroup = dispatch_group_create()

for i in 0..<count {


getImage(i, completion: { (image:NSData) in


print("Finish Request \(i)")



dispatch_group_notify(myGroup, dispatch_get_main_queue(), {

completion(data: datas)


private func getImage(number:Int, completion:(image:NSData)->()){

let storage = FIRStorage.storage()

//Reference to Firebase Profile Picture Storage
let storageRef = storage.referenceForURL("gs://mannacatering-addcb.appspot.com")

print("Initiating Image Download")

let galleryPicRef = storageRef.child("Gallery/\(selectedGallery!)/g\(String(number)).jpg")

//Download Image
galleryPicRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
if (error != nil) {
print("fail to download image")


dispatch_async(dispatch_get_main_queue(), {

print("Dispatching image")


I split them up into 2 separate functions because I tried to manage them in a single function and the order is in a mess as well and I thought this might work but apparently not. I hope you guys can help me out.. I've spent the whole day trying to solve this.

Thanks and best regards,


Instead of storing your data in an array, store it in a dictionary. The key can be the number i or however you want to refer to an image when you use it.