2011-03-26 62 views
0

任何人都可以请提供或告诉我如何在本地文件不存在的情况下异步下载PDF。ASIHTTP asynchrounous pdf下载

我的代码如下:

NSURL *url = [NSURL URLWithString:@"http://www.url.com"]; 
NSString *tempDownloadPath = [[self documentsDirectory] 
           stringByAppendingString:@"test.pdf"]; 
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
[request setDownloadDestinationPath:[self documentsDirectory]]; 
[request setTemporaryFileDownloadPath:tempDownloadPath]; 
[request setDelegate:self]; 
[request startAsynchronous]; 

一旦它完成我尝试把这个

[aWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[self documentsDirectory] pathForResource:@"test" ofType:@"pdf"]isDirectory:NO]]]; 

但是它要么崩溃或者不加载我的网页视图内什么。 有什么建议吗?

带有自DOCUMENTSDIRECTORY

回答

3

你需要把你的文件放在UIWebView可以访问的地方,然后指向它。你没有包括你如何创建[self documentsDirectory],你只是追加一个字符串,而不是使用附加路径追加临时位置。您也没有告诉ASIHTTPRequest最终文档使用的实际文件名,只是放入目录,所以它甚至可能不会被保存。此外,UIWebView加载请求不正确。

下面介绍如何创建告诉ASIHTTPRequest放置文件的路径。

编辑以更改临时文件位置的NSCachesDirectory代替,这样它会导致下载失败时与部分数据

// SAVED PDF PATH 
// Get the Document directory 
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
// Add your filename to the directory to create your saved pdf location 
NSString *pdfLocation = [documentDirectory stringByAppendingPathComponent:@"test.pdf"]; 

// TEMPORARY PDF PATH 
// Get the Caches directory 
NSString *cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
// Add your filename to the directory to create your temp pdf location 
NSString *tempPdfLocation = [cachesDirectory stringByAppendingPathComponent:@"test.pdf"]; 

// Tell ASIHTTPRequest where to save things: 
[request setTemporaryFileDownloadPath:tempPdfLocation];  
[request setDownloadDestinationPath:pdfLocation]; 

那么当你委托收到文件下载的通知被自动清除出完成后,再次使用正确的方法告诉UIWebView在哪里找到文件。

// If you've stored documentDirectory or pdfLocation somewhere you won't need one or both of these lines 
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
NSString *pdfLocation = [documentDirectory stringByAppendingPathComponent:@"test.pdf"]; 

// Now tell your UIWebView to load that file 
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfLocation]]]; 
+1

@Alx是否为您工作? – 2011-03-31 02:48:45

1

编辑我认为错误是你下载文件到文件的目录,然后你要找的主包中的文件。您应该在文档目录中查找它。

+0

你的意思是self文件目录?我试过之后仍然没有任何东西 – 2011-03-26 20:42:18

+0

Erik是对的,它绝对不会在你的包中(当应用程序被捆绑并发送到Apple时,捆绑项目只是那里的东西)。你如何获取你的文档目录?你可能会把它放在UIWebView不允许看的地方。 – 2011-03-26 20:47:11

+0

@Alx,这个包是只读的,所以你下载的任何东西都不会在这个包中找到。 – 2011-03-26 20:48:03