如何从UIWebView下载文件并再次打开

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从UIWebView下载文件并再次打开相关的知识,希望对你有一定的参考价值。

我如何创建一个“下载管理器”,它可以检测您点击的链接(在UIWebView中)何时文件结尾为“.pdf”,“。png”,“。jpeg”,“。ifff”,“。gif” ,“。doc”,“。dococ”,“。pt”,“。ptx”,“。xls”和“.xlsx”,然后会打开一个UIActionSheet,询问您是否要下载或打开。如果选择下载,则会将该文件下载到设备。

该应用程序的另一部分将在UITableView中有一个下载文件列表,当您点击它们时,它们将显示在UIWebView中,但当然是离线的,因为它们将在本地加载,因为它们本来会被下载。

请参阅http://itunes.apple.com/gb/app/downloads-lite-downloader/id349275540?mt=8以更好地了解我要做的事情。

这样做的最佳方式是什么?

答案

在UiWebView的委托中使用- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType方法来确定何时加载资源。

当调用方法时,你只需要解析参数(NSURLRequest *)request中的URL,如果它是你想要的类型之一则返回NO并继续你的逻辑(UIActionSheet)或如果用户只是点击一个简单的html链接就返回YES文件。

说得通?

Edit_:为了更好地理解快速代码示例

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
     if(navigationType == UIWebViewNavigationTypeLinkClicked) {
          NSURL *requestedURL = [request URL];
          // ...Check if the URL points to a file you're looking for...
          // Then load the file
          NSData *fileData = [[NSData alloc] initWithContentsOfURL:requestedURL;
          // Get the path to the App's Documents directory
          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
          NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
          [fileData writeToFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, [requestedURL lastPathComponent]] atomically:YES];
     } 
}

Edit2_:在我们讨论了聊天中的问题之后,我已经更新了代码示例:

- (IBAction)saveFile:(id)sender {
    // Get the URL of the loaded ressource
    NSURL *theRessourcesURL = [[webView request] URL];
    NSString *fileExtension = [theRessourcesURL pathExtension];

    if ([fileExtension isEqualToString:@"png"] || [fileExtension isEqualToString:@"jpg"]) {
        // 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 {
            // File could notbe loaded -> handle errors
        }
    } else {
        // File type not supported
    }
}

/**
    Just a small helper function
    that returns the path to our 
    Documents directory
**/
- (NSString *)documentsDirectoryPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];
    return documentsDirectoryPath;
}

以上是关于如何从UIWebView下载文件并再次打开的主要内容,如果未能解决你的问题,请参考以下文章

如何在 UIWebView 中打开文件?

如何从url数组循环下载swift4中的pdf

如何从 UIWebView 打开 safari.app 中的外部链接?

如何从 Swift 3 中的 UIWebview 中的链接打开另一个视图?

如何从 UIWebView 在 iPhone 上创建 .webarchive 文件?

如何向自定义 UIWebview 添加“打开方式”功能?