我試圖從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!)
})
}
}
}
我將它們分割成兩個獨立的功能,因爲我想在一個單一的功能來管理他們的順序是一個爛攤子,以及和我想這可能工作,但顯然不是。
感謝Philip。這完全解決了我的問題。認爲我沒有考慮到這一點,我覺得很愚蠢...... –
有時它只需要一對不同的眼睛。 –