带异步调用的循环

时间:2019-08-18 19:07:00

标签: swift firebase for-loop firebase-storage dispatch

我试图遍历图像的链接,并从Firebase下载图像,然后将它们放入数组中。但是,我无法使调度小组正常工作。

基本上,有dbAnims包含指向Firebase Storage中文件夹的链接。存储中的每个文件夹都包含多个图像。我需要遍历该文件夹,然后将文件夹中的每个图像下载到各自的数组中(每个数组都是我循环播放动画的图像数组)。

let myGroup = DispatchGroup()
    // dbAnim contains links to folders containing 4-6 images each
    func loopThroughDBAnims(_ dbAnims: [DbAnimation]) {
        for anim in dbAnims {
            addOverlays(dbAnim: anim)
        }
    }

    func addOverlays(dbAnim: DbAnimation) {

        self.myGroup.enter()
        var tupleArr = [(Int, UIImage)]()
        MY_STORAGE.STORAGE.reference(forURL: dbAnim.linkString).listAll(completion: { (folders, error) in
            if let error = error {
                print("ERROR FB STORAGE: \(error)")
            } else {
                self.myGroup.leave()
                for (index, file) in folders.items.enumerated() {
                    //print(index)
                    self.myGroup.enter()
                    file.getData(maxSize: 1 * 1024 * 1024) { data, error in
                        if let error = error {
                            print("ERROR getting image: \(error)")
                        } else {
                            self.myGroup.leave()
                            let image = UIImage(data: data!)
                            tupleArr.append((Int(file.fullPath.slice(from: "frame_", to: ".png")!)!, image!))
                            print("Finished request \(index)")
                            if index == folders.items.count - 1 {
                                let overlay = Overlay(duration: dbAnim.duration, tupleArr: tupleArr)
                                self.overlays.append(overlay)
                            }
                        }
                    }
                }
            }
        })
        self.myGroup.notify(queue: .main) {
            print("Finished all requests.")
        }
    }

0 个答案:

没有答案