iOS在另一个应用程序中打开PDF文件

时间:2017-11-10 13:15:06

标签: ios objective-c pdf

我想在另一个应用程序中共享/打开我的应用程序中的PDF文件。

我想与之分享的两个主要应用是Dropbox& PDF专家。

这是我正在使用的代码,但它无效。例如,如果我尝试通过airdrop,电子邮件和WhatsApp共享文件,它不会共享任何内容

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf", @"test"]];
NSURL *URL = [NSURL fileURLWithPath:fullPath];
NSArray *activityItems = [NSArray arrayWithObjects:URL, nil];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];

[self presentViewController:activityViewController animated:YES completion:nil];

test.pdf文件在我的项目中。

如果有办法从服务器共享PDF?它会更好,所以我不需要在我的应用程序中下载该文件然后共享它。

1 个答案:

答案 0 :(得分:1)

试试这个。

// In your header. MyViewController.h
@interface MyViewController : UIViewController 
                              <UIDocumentInteractionControllerDelegate>
{
UIDocumentInteractionController *docController;
}

// In your implementation. MyViewController.m Open Results is hooked up 
to a button.
- (void)openResults
{
 // Generate PDF Data.
 NSData *pdfData = [self makePDF];

 // Create a filePath for the pdf.
 NSArray *paths = 
 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
 NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSString *filePath = [documentsDirectory 
 stringByAppendingPathComponent:@"Report.pdf"];

 // Save the PDF. UIDocumentInteractionController has to use a physical 
 PDF, not just the data.
 [pdfData writeToFile:filePath atomically:YES];

 // Open the controller.
 docController = [UIDocumentInteractionController 
 interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
 docController.delegate = self;
 docController.UTI = @"com.adobe.pdf";
 [docController presentOpenInMenuFromBarButtonItem:shareButton 
 animated:YES];
 }