2016-03-07 155 views
0

我有一些問題,當生病從表單創建一個PDF - 有多個頁面(多達20,我想在後臺線程創建文件)等待PDF文件完成?

我想使用完成處理程序,所以當該文件創建我想要顯示在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()完成)

回答

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