2010-04-16 488 views

回答

9

您可以使用NSURL class将pdf文件下载到您的文档目录中,而无需在Safari中打开它(随后终止您自己的应用程序)。

UIWebView可以很容易地显示外部PDF和本地文件(只需指向正确的文件路径),因此您甚至可以将PDF下载到您的文档文件夹,然后在本地缓存中显示它以后的日期。

下面加

对于一个简单的例子一些示例代码,你会发现这是你的应用程序可以接受的;这会将文件下载到您的文档文件夹,但使用阻止功能(initWithContentsOfURL),因此您可能会遇到大文件/慢连接的问题:

(此代码应该是您需要的全部,但您可能希望创建一个函数来处理这个步骤/处理内存/检查错误等)

//Grab the file from the URL 

NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.website.com/doc1.pdf"]]; 

// Put the data into a file in your Documents folder 

NSString *docFolder = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]]; 

NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"doc1.pdf"]; 

[pdfData writeToFile:filePath atomically:YES]; 

为了让你建立一个基本的样本,下面的代码就足够了,从您的文档文件夹中的一个内显示PDF文件webview:

-(void)viewDidLoad 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"doc.pdf"]; 

// ... 

    webView.scalesPageToFit = YES; 
    webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); 

    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfPath isDirectory:NO]]]; 

} 

如果要直接从网站(而不是本地文件)显示PDF,则可以让pdfPath包含文件的完整URL。

+0

嗨,davbryn你有任何例子或weblink教程或代码来做这种东西...我想转换我的UIWebView内容在pdf中,并将其存储在文档目录中以便以后使用... – 2010-04-19 04:50:54

+0

当然,已经为你更新了答案。 – davbryn 2010-04-19 07:34:05

+0

非常感谢davbryn ... – 2010-04-19 11:30:26

0

Safari将打开一个PDF文件,但不保存它以备以后检索。