我可以在创建PDF期间更新UI吗?

时间:2013-07-07 18:27:43

标签: ios multithreading pdf-generation background-process

我正在尝试为QuickLook框架创建多页PDF以进行打印,但在创建时无法更新UI(我希望用户得到剩余页数的倒计时)。下面的代码是我正在尝试使用线程睡眠代码进行代码的简化版本,这需要一段时间才能呈现。

- (void) testPDF
{
    CGRect pageSize = CGRectMake(0.0f, 0.0f, 595.28, 841.89);

    UIGraphicsBeginPDFContextToFile([self filePath], pageSize, nil);
    {
        UIGraphicsBeginPDFPage();

        for( int y = 0; y < 5; y++ )    {
            self.pageLabel.text = [NSString stringWithFormat:@"%d", y];

            [[UIColor grayColor] set];
            [@"test string" drawAtPoint:CGPointMake(0, y*20) withFont:[UIFont systemFontOfSize:15]];

            NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 1.0];
            [NSThread sleepUntilDate:future];
        }
    }
    UIGraphicsEndPDFContext();
}

现在我的代码呈现PDF但不更新IBOutlet'pageLabel',我们将非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

在后台线程上运行PDF创建,但更新主(也称为UI)线程上的UI。完成PDF创建后,调用方法(在本例中为presentPDF)将PDF呈现给用户,确保在执行此操作之前切换到主线程。例如:

-(void)presentPDF{

    // Make sure this runs on the main (UI) thread
    dispatch_sync(dispatch_get_main_queue(), ^{

        //Insert code to present the PDF...

    });
}

- (void) testPDF
{

    // Run on background thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        CGRect pageSize = CGRectMake(0.0f, 0.0f, 595.28, 841.89);

        UIGraphicsBeginPDFContextToFile([self filePath], pageSize, nil);
        {
            UIGraphicsBeginPDFPage();

            for( int y = 0; y < 5; y++ ){

                // Make sure this runs on the main (UI) thread
                dispatch_sync(dispatch_get_main_queue(), ^{
                    self.pageLabel.text = [NSString stringWithFormat:@"%d", y];

                });

                [[UIColor grayColor] set];
                [@"test string" drawAtPoint:CGPointMake(0, y*20) withFont:[UIFont systemFontOfSize:15]];

                NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 1.0];
                [NSThread sleepUntilDate:future];
            }
        }
        UIGraphicsEndPDFContext();

        [self presentPDF];
    });
}