在iphone SDK中从uiwebview下载文件

有什么办法从UIWebView下载文件,我在我的IBAction事件上使用这个代码

 - (IBAction)saveFile:(id)sender { // Get the URL of the loaded ressource NSURL *theRessourcesURL = [[self.webDisplay request] URL]; NSString *fileExtension = [theRessourcesURL pathExtension]; if ([fileExtension isEqualToString:@"png"] || [fileExtension isEqualToString:@"jpg"] || [fileExtension isEqualToString:@"pdf"] || [fileExtension isEqualToString:@"html"]) { // Get the filename of the loaded ressource form the UIWebView's request URL NSString *filename = [theRessourcesURL lastPathComponent]; NSLog(@"Filename: %@", filename); // Get the path to the App's Documents directory NSString *docPath = [self documentsDirectoryPath]; // Combine the filename and the path to the documents dir into the full path NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docPath, filename]; // Load the file from the remote server NSData *tmp = [NSData dataWithContentsOfURL:theRessourcesURL]; // Save the loaded data if loaded successfully if (tmp != nil) { NSError *error = nil; // Write the contents of our tmp object into a file [tmp writeToFile:pathToDownloadTo options:NSDataWritingAtomic error:&error]; if (error != nil) { NSLog(@"Failed to save the file: %@", [error description]); } else { // Display an UIAlertView that shows the users we saved the file :) UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:@"File saved" message:[NSString stringWithFormat:@"The file %@ has been saved.", filename] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [filenameAlert show]; [filenameAlert release]; } } else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"File could not be loaded" delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil]; [alert show]; [alert release]; // File could notbe loaded -> handle errors } } else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"File type not supported" delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil]; [alert show]; [alert release]; // File type not supported } 

}这段代码在UIWebView打开文件,我想下载,当我按下button打开的文件得到保存。 但我想我的UIWebView的行为像普通的浏览器,当下载链接出现在它和用户按下它, UIWebView显示对话框的选项打开它或保存它,如果用户按下保存文件自动保存,如果用户按下打开文件应在UIWebView打开。

您可以在您的UIWebViewDelegate提供webView:shouldStartLoadWithRequest ,以便每次用户将要移动到另一个网页时,您都有机会检查链接是什么样的:

  - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { if ([[[request URL] scheme] isEqual:@"http"] && [[[request URL] pathExtension]...]) <your download/save code here> return NO; //-- no need to follow the link } return YES; //-- otherwise, follow the link }