在Swift中完成多个异步功能后执行操作

时间:2020-06-07 18:59:35

标签: ios swift firebase

我正在尝试从Firebase存储下载多个文件,并将它们添加到textView中。我想在调用功能addFilesIntoNote之前使用功能DownloadFile从Firebase Storage异步下载所有文件。我已经尝试使用调度组执行此操作:

override func viewDidLoad() {
    let group = DispatchGroup()

    DispatchQueue.main.async {
        if let attributes = self.noteAttributes {
            for attribute in attributes {
                group.enter()
                self.downloadFile(fileName: attribute.fileName) {
                    group.leave()
                }
            }
        }
    }

    group.notify(queue: .main) {
        self.addFilesIntoNote()
    }
}

func downloadFile(fileName: String, completionHandler: @escaping () -> Void) {
    let localURL = DocumentsDirectory.appendingPathComponent(fileName)
    let filePath = rtfNote!.noteID! + "/" + fileName
    let fileRef = storage.reference(withPath: filePath)

    if !fileManager.fileExists(atPath: localURL.path) {
        let downloadTask = fileRef.write(toFile: localURL) { url, error in
            if let error = error {
                print("error")
            } else {
                completionHandler()
            }
        }
    }
}

但是,在下载所有文件之前,它仍然会继续调用addFilesIntoNote函数。 在调用addFilesIntoNote函数之前,如何确保所有文件都已完全下载?

1 个答案:

答案 0 :(得分:1)

即使在发生错误并且您不需要主队列的情况下,也可以执行消防完成处理程序

这样更改代码

override func viewDidLoad() {
    let group = DispatchGroup()

        if let attributes = self.noteAttributes {
            for attribute in attributes {
                group.enter()
                self.downloadFile(fileName: attribute.fileName) {
                    group.leave()
                }

        }
    }

    group.notify(queue: .main) {
        self.addFilesIntoNote()
    }
}

func downloadFile(fileName: String, completionHandler: @escaping () -> Void) {
    let localURL = DocumentsDirectory.appendingPathComponent(fileName)
    let filePath = rtfNote!.noteID! + "/" + fileName
    let fileRef = storage.reference(withPath: filePath)

    if !fileManager.fileExists(atPath: localURL.path) {
        let downloadTask = fileRef.write(toFile: localURL) { url, error in
            if let error = error {
                print("error")

            } 

             completionHandler()
        }
    }
}