如何在iOS UIWebView中显示带有PDF内容的NSData?

我试图通过UIWebView在我的iPad应用程序中显示PDF,如下所示。

 NSData * responseData = [NSURLConnection sendSynchronousRequest:mutableUrlRequest returningResponse:nil error:nil]; [pdfWebView loadData:responseData MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil]; 

但是这不起作用。 这是一个正确的方式来显示? 如果没有人可以指导我在UIWebView或任何其他有用的方法显示PDF。

谢谢 !

得到了我的问题的答案。 下面的线会做魔术。

  [webview loadData:PdfContent MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil]; 

将其保存到带有PDF后缀的文件的临时目录中,并从此处打开。

如何将NSData(pDF文件)保存到文档目录中:

 NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *documentFolderPath = [searchPaths objectAtIndex: 0]; NSString *imagePath = [documentFolderPath stringByAppendingPathComponent:@"yourPdfFileName.pdf"]; NSFileManager *filemanager=[NSFileManager defaultManager]; if(![filemanager fileExistsAtPath:filePath]) [[NSFileManager defaultManager] createFileAtPath:filePath contents: nil attributes: nil]; NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath]; [handle writeData:data]; 

SWIFT3

 webView.load(data, mimeType: "application/pdf", textEncodingName: "UTF-8", baseURL: URL(string: "You can use URL of any file in your bundle here")!) 

如果您的应用程序捆绑了PDF文件(在本例中名为“document.pdf”):

 UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)]; NSString *path = [[NSBundle mainBundle] pathForResource:@"document" ofType:@"pdf"]; NSURL *targetURL = [NSURL fileURLWithPath:path]; NSURLRequest *request = [NSURLRequest requestWithURL:targetURL]; [webView loadRequest:request]; [self.view addSubview:webView]; [webView release]; 

您可以在这里find更多信息:技术QA1630:使用UIWebView显示select的文档types。

任何你没有使用Quick Look Framework或UIDocumentInteractionController的理由? 他们能够为用户提供比WebView更多的function和更less的节点。

这里是链接到苹果的文档: https : //developer.apple.com/library/ios/documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Articles/UsingtheQuickLookFramework.html

https://developer.apple.com/library/ios/documentation/uikit/reference/UIDocumentInteractionController_class/Reference/Reference.html

如果您想要从应用程序的文件系统中呈现PDF,则无需烦恼! 只要确保您存储的PDF文件具有适当的'.pdf'扩展名,然后以完整path将其提供给QLPreviewController:

 self.contentURL = [NSURL fileURLWithPath:fullPath];