gpt4 book ai didi

ios - 在闭包中获取变量是否完整?

转载 作者:行者123 更新时间:2023-11-30 11:50:02 24 4
gpt4 key购买 nike

我有一个创建 PDF 文件的闭包函数 - 这可能需要一些时间,并且包含一个进度函数。我的问题是,我如何在关闭之外收到“进度”?

例如:

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
}

我用以下方式调用我的函数:

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
}
}

最佳答案

这是一个使用 Playground 的基本示例,应该可以帮助您:

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

输出:

10.0
20.0
30.0
40.0
50.0
60.0
70.0
80.0
90.0
100.0
true

关于ios - 在闭包中获取变量是否完整?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48433382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com