UIDocumentInteractionController控制器问题

时间:2013-07-27 10:12:08

标签: iphone ios

我想从webservice下载pdf文件并使用 UIDocumentInteractionController 打开它。我可以这样做吗?我使用以下代码进行下载

NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"myurl/abc.pdf"]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"abcd.pdf"];
pdfData writeToFile:filePath atomically:YES];

现在我该怎么做才能用 UIDocumentInteractionController

打开它

1 个答案:

答案 0 :(得分:3)

您可以使用以下代码在UIDocumentInteractionController中打开PDF这是一个显示来自NSBundle的pdf的示例,您也可以在文档目录中显示,就像我们显示图像一样。您需要完整的文档路径,并使用NSURL将其转换为fileURLWithPath: -

yourViewController.h 文件中: -

@interface yourViewController : UIViewController<UIDocumentInteractionControllerDelegate>
{
     UIDocumentInteractionController *documentationInteractionController; 
}

在** yourViewController.m 文件中: - **

    -(void) viewDidAppear:(BOOL)animated {

            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
            NSString *documentsDirectory = [paths objectAtIndex:0]; 
            NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"abcd.pdf"];

            NSURL *pdfUrl = [NSURL fileURLWithPath:filePath];
            documentationInteractionController = [UIDocumentInteractionController interactionControllerWithURL:pdfUrl];
            documentationInteractionController.delegate = self;
            [documentationInteractionController presentPreviewAnimated:YES];

        [super viewDidAppear:animated];
    }

UIDocumentInteractionController

的代表
    - (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller {
        return self;
    }

Demo link 快乐的编码... :)