我目前正在开发一个与pdf一起工作的Cocoa应用程序,并使用Apple的PDFKit来完成这项工作。保存PDF被证明是一个问题,因为我想在发生这种情况时显示进度条,这似乎不可能使用标准writeToURL:
方法。所以,我转而使用中央调度。
问题是,dataRepresentation
方法用于获得NSData写入是非常缓慢的转换任何大于~3MB的PDF到NSData,所以进度条停滞了几秒钟,而我的程序正在等待数据,这似乎使用户认为程序已经完全停滞。我真的不希望他们那样想。
我的问题是,我能做些什么来加速dataRepresentation
方法,或者向用户报告其进度?
这是我最后写的中央调度代码:
NSData *pdf = [doc dataRepresentation]; // R-e-a-l-l-y S-l-o-w
dispatch_queue_t queue = dispatch_get_current_queue();
dispatch_data_t dat = dispatch_data_create([pdf bytes], [pdf length], queue, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
__block dispatch_io_t channel =
dispatch_io_create_with_path(DISPATCH_IO_STREAM,
[path UTF8String], // Convert to C-string
O_WRONLY, // Open for writing
0, // No extra flags
queue,
^(int error){
// Cleanup code for normal channel operation.
// Assumes that dispatch_io_close was called elsewhere.
if (error == 0) {
dispatch_release(channel);
channel = NULL;
}
});
// The next two lines make sure that the block in dispatch_io_write
// gets called about 60 times, so that it can update the progress bar.
dispatch_io_set_low_water(channel,[pdf length]/60);
dispatch_io_set_high_water(channel,[pdf length]/60);
dispatch_io_write(channel,
0,
dat,
queue,
^(bool done, dispatch_data_t data, int error) {
if (data) {
// Increment progress bar
}
if (error) {
// Handle errors
}
if (done) {
dispatch_io_close(channel, NULL);
}
});
dispatch_release(dat);
dispatch_release(queue);
使用PDFDocumentDidBeginPageWriteNotification
和PDFDocumentDidEndPageWriteNotification
通知,它们在-writeToURL:
期间发送。通知告诉您正在处理哪个页面,您可以将其与文档中的页面总数进行比较,以显示进度。