等到PDF文件完成?

时间:2016-03-07 01:12:31

标签: ios swift

我从表单生成PDF时遇到一些问题 - 有多个页面(最多20个,我想在后台线程中创建文件)

我想使用一个完成处理程序,所以当创建文件时,我想在QLPreviewController中显示它。但是当生病时不使用等待/休眠功能时,它总是会因错误而崩溃,文件尚未完成。

所以目前:

func exportPDF(fileName:String, task: completionHandler:(success:Bool) -> Void) {
    // run on background
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

        UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);

        // write pages

        UIGraphicsEndPDFContext()
        completionHandler(success:true) // how do i wait till file has finshed?
    })
}

我打电话:

exportPDF(filepath, task: task, completionHandler:{(success:Bool) -> Void in

        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC)))
        let queue = dispatch_get_main_queue()

        dispatch_after(when, queue) {

            if self.finish == true {

                let preview = ExportQLPreviewController()
                preview.task = self.task
                preview.dataSource = self
                preview.preferredContentSize = CGSizeMake(700, 700)
                preview.emaildelegate = self.emaildelegate

                self.navigationController?.pushViewController(preview, animated: false)


            } else {

                let preview = QLPreviewController()
                preview.dataSource = self
                preview.preferredContentSize = CGSizeMake(700, 700)
                self.navigationController?.pushViewController(preview, animated: false)

            }

        }

})

有什么问题吗?怎么病得等到我的档案写完了?因为没有"等待"它总是崩溃的方法(看起来完成处理程序不会等到UIGraphicsEndPDFContext()完成)

1 个答案:

答案 0 :(得分:0)

尝试使用dispatch_group。

    //Create a dispatch_group
    let taskGroup = dispatch_group_create()
    //Set a start label before your function
    dispatch_group_enter(taskGroup)
    //Put a end label after your function finished
    dispatch_group_leave(taskGroup)
    //And dispatch_group_notify will be called while
    //number of enter labels = number of end labels
    dispatch_group_notify(taskGroup, dispatch_get_main_queue(), {
        //Do what you want after task is finished.
    })
像这样

enter image description here