2011-11-10 19 views
5

¿Hay alguna manera de descargar archivos desde UIWebView estoy utilizando este código en mi caso IBActiondescarga de archivos desde UIWebView en iPhone SDK

- (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 
} 

} este código abrir el archivo en UIWebView, que quiero descargar y cuando presiono el botón, el archivo abierto se guarda. pero quiero mi UIWebView a comportarse como navegador normal, cuando el enlace de descarga aparece en ella y pulse el usuario que, UIWebView espectáculo de diálogo con la opción de abrirlo o guardarlo si el usuario pulsa guardar el archivo de conseguir guardar automáticamente y si el usuario pulsa archivo abierto debe abrir en UIWebView.

Respuesta

6

Puede proporcionar webView:shouldStartLoadWithRequest en su UIWebViewDelegate de modo que cada vez que el usuario está a punto de pasar a otra página web, usted tiene la oportunidad de ver lo que el enlace se parece a:

- (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 
    } 
+1

Gracias Sergio por su respuesta y por su respuesta me guíe mucho su línea comentada :) –

+0

@Sergio Si trato de descargar un archivo (puede ser desde un servidor de yahoo/cambio) que tendrá como esquema https ** ** negrita ** ** negrita y la pathExtension es una cadena aleatoria para, por ejemplo. ashx, etc. ...! ¿Cómo solicito la descarga de dichos archivos? Alguna idea sobre esto? – Nirav

Cuestiones relacionadas