在Closure内完成变量吗?

时间:2018-01-24 23:30:15

标签: ios swift

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

例如:

AssetManager

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

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
}

1 个答案:

答案 0 :(得分:0)

以下是一个使用游乐场的基本示例,可以帮助您:

    [
    {
   "name": "Test1",
    "description": "testings",
    "unitname": simple,
     "ID": 02,
     "val": "item"
     },
      {
     "name": "Test2",
     "description": "testing",
      "unitname": simple3,
       "ID": 23,
       "val": "item"
     }

         {
         "name": "Test3",
             "description": "testing",
            "unitname": simple4,
            "ID": 23,
            "val": "item"
            }
       {
          "name": "Test4",
         "description": "testing",
         "unitname": simple6,
           "ID": 23,
           "val": "item"
             } 
           ]

输出:

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