I have some problems when ill create a PDF from a form - there are multiple pages (up to 20 and i want to create the file in a background thread)
生病时从表单创建PDF有一些问题 - 有多个页面(最多20个,我想在后台线程中创建文件)
I would like to use an completion handler, so when the file is created i want to show it in an QLPreviewController. But when ill use no wait/sleep function it always crashes with an error, that the file is not already finished.
我想使用一个完成处理程序,所以当创建文件时,我想在QLPreviewController中显示它。但是当生病时不使用等待/睡眠功能时,它总是会因错误而崩溃,文件尚未完成。
So at the moment:
所以目前:
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?
})
}
Ill call with:
生病的电话:
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)
}
}
})
Is there something wrong? How can ill wait till my file has written? Because without the "wait" method it always crashes (it looks like that the completion handler does not wait till the UIGraphicsEndPDFContext() finish)
有什么不对?怎么病得等到我的档案写完了?因为没有“等待”方法它总是崩溃(看起来完成处理程序不会等到UIGraphicsEndPDFContext()完成)
1 个解决方案
#1
0
Try using dispatch_group.
尝试使用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.
})
like this
#1
0
Try using dispatch_group.
尝试使用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.
})
like this