I have a Closure Function which creates a PDF File - that could take some time and there is a progress function included. My problem is, how can i receive that "progress" outside my closure?
For example:
func makeReport(fileName:String, task: Task, completion:@escaping (_ success:Bool) -> Void) {
.....
let _ = pdf.generatePDF(fileName, progress: {
progress in
print(progress) // here is my progress
})
completion(true) // returns when the file is created, so i know that i am now able to show the PDF
}
I call my function with:
pdfCreator.makeReport(fileName: filename, task: self.task, completion: {success in
// any chance to get my progress to update a spinner for example?
if success == true {
// file is here
}
}
Here is a basic example using a playground that should help you out:
func makeReport(fileName: String, progress: @escaping (_ progress: CGFloat) -> Void, completion: @escaping (_ success: Bool) -> Void) {
var progressOfTask: CGFloat = 0.0
let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
progressOfTask += 10
progress(progressOfTask)
if progressOfTask == 100.0 {
completion(true)
timer.invalidate()
}
}
timer.fire()
}
makeReport(fileName: "", progress: { progress in
print(progress)
}, completion: { success in
print(success)
})
PlaygroundPage.current.needsIndefiniteExecution = true
Output:
10.0
20.0
30.0
40.0
50.0
60.0
70.0
80.0
90.0
100.0
true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.