如何从 UIWebView 下载文件并再次打开 [英] How to download files from UIWebView and open again

查看:17
本文介绍了如何从 UIWebView 下载文件并再次打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个下载管理器"来检测您点击的链接(在 UIWebView 中)何时具有以 ".pdf"、".png"、".jpeg"、".tiff 结尾的文件", ".gif", ".doc", ".docx", ".ppt", ".pptx", ".xls" and ".xlsx" 然后会打开一个 UIActionSheet 询问你想下载或打开.如果您选择下载,它将将该文件下载到设备.

应用的另一部分将在 UITableView 中列出已下载的文件,当您点击它们时,它们将显示在 UIWebView 中,但当然是离线的,因为它们会像下载一样在本地加载.

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

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

解决方案

使用方法 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 在您的 UiWebView 的委托中确定它想要加载资源的时间.

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

有意义吗?

编辑_:为了更好地理解快速代码示例

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {if(navigationType == UIWebViewNavigationTypeLinkClicked) {NSURL *requestedURL = [请求 URL];//...检查 URL 是否指向您正在查找的文件...//然后加载文件NSData *fileData = [[NSData alloc] initWithContentsOfURL:requestedURL;//获取应用程序文档目录的路径NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0];//获取文档文件夹[fileData writeToFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, [requestedURL lastPathComponent]] 原子:YES];}}

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

- (IBAction)saveFile:(id)sender {//获取加载资源的URLNSURL *theRessourcesURL = [[webView 请求] URL];NSString *fileExtension = [theRessourcesURL pathExtension];if ([fileExtension isEqualToString:@"png"] || [fileExtension isEqualToString:@"jpg"]) {//从 UIWebView 的请求 URL 中获取加载资源的文件名NSString *filename = [theRessourcesURL lastPathComponent];NSLog(@"文件名:%@", 文件名);//获取应用程序文档目录的路径NSString *docPath = [self 文档目录路径];//将文件名和文件目录的路径组合成完整路径NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docPath, 文件名];//从远程服务器加载文件NSData *tmp = [NSData dataWithContentsOfURL:theRessourcesURL];//如果加载成功则保存加载的数据如果(tmp != 零){NSError *error = nil;//将我们的 tmp 对象的内容写入文件[tmp writeToFile:pathToDownloadTo options:NSDataWritingAtomic error:&error];如果(错误!= nil){NSLog(@"保存文件失败:%@", [错误说明]);} 别的 {//显示一个 UIAlertView,显示我们保存文件的用户:)UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:@"文件已保存" message:[NSString stringWithFormat:@"文件 %@ 已保存.", filename] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];[文件名提示显示];[文件名警报发布];}} 别的 {//无法加载文件 ->处理错误}} 别的 {//不支持的文件类型}}/**只是一个小辅助函数返回到我们的路径文件目录**/- (NSString *)documentsDirectoryPath {NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectoryPath = [paths objectAtIndex:0];返回文档目录路径;}

How can I create a "download manager" which would detect when a link you tap (in a UIWebView) has the file ending ".pdf", ".png", ".jpeg", ".tiff", ".gif", ".doc", ".docx", ".ppt", ".pptx", ".xls" and ".xlsx" and then would open a UIActionSheet asking you if you would like to download or open. If you select download, it will then download that file to the device.

Another section of the app would have a list of downloaded files in a UITableView and when you tap on them, they will show in a UIWebView, but of course offline because they would load locally as they would have been downloaded.

See http://itunes.apple.com/gb/app/downloads-lite-downloader/id349275540?mt=8 for a better understanding of what I am trying to do.

What is the best way of doing this?

解决方案

Use the method - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType in your UiWebView's delegate to determine when it wants to load resource.

When the method get's called, you just need to parse the URL from the parameter (NSURLRequest *)request, and return NO if it's one of your desired type and continue with your logic (UIActionSheet) or return YES if the user just clicked a simple link to a HTML file.

Makes sense?

Edit_: For better understanding a quick code example

- (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_: I've updated the code sample after our dicussion about your issues in the chat:

- (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 下载文件并再次打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆