我正在尝试从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函数之前,如何确保所有文件都已完全下载?
答案 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()
}
}
}