2016-08-28 130 views
0

我试图从Firebase存储下载一批图像时遇到问题。基本上,因为文件大小不同,图像不会被正确地添加到图像阵列中,导致图像出现我想要的错误顺序。下面是代码Firebase存储异步图像下载的顺序不正确

import Foundation 
import FirebaseStorage 

class GalleryCellDetailedData { 
    var selectedGallery:String? 
    var count:Int 

    init(selectedGallery:String?,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 { 
      dispatch_group_enter(myGroup) 
      getImage(i, completion: { (image:NSData) in 
       datas.append(image) 
       print("Finish Request \(i)") 
       dispatch_group_leave(myGroup) 
      }) 
     } 

     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") 
       completion(image:data!) 
      }) 
     } 
    } 
} 

我将它们分割成两个独立的功能,因为我想在一个单一的功能来管理他们的顺序是一个烂摊子,以及和我想这可能工作,但显然不是。

回答

2

不是将数据存储在数组中,而是将其存储在字典中。密钥可以是数字i,或者您希望在使用图像时参考图像。

+0

感谢Philip。这完全解决了我的问题。认为我没有考虑到这一点,我觉得很愚蠢...... –

+0

有时它只需要一对不同的眼睛。 –