2011-03-26 65 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