【问题标题】:How to download files from UIWebView and open again如何从 UIWebView 下载文件并再次打开
【发布时间】:2011-11-14 16:59:49
【问题描述】:

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

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

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

最好的方法是什么?

【问题讨论】:

    标签: ios iphone download uiwebview


    【解决方案1】:

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

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

    有道理吗?

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

    【讨论】:

    • 当您拥有资源 URL 时,只需使用 NSURLRequest 下载该文件并将其保存在本地。在 SO 或 Google 上搜索这里,有很多教程 :)
    • 我已经搜索了负载,但找不到任何说明如何从本地 UIWebView 下载文件的内容:(
    • 因为不是从 UIWebView 下载文件,而是从 URL 下载文件。您可以从我在回答中提到的方法的请求参数中获取 URL。
    • 好的,那么我将如何“使用 NSURLConnection 下载文件”? :-)
    • 文档是你的朋友 ;-) developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/…。在 "- (void)connectionDidFinishLoading:(NSURLConnection *)connection" 方法中,您可以使用 NSData 的 "writeToFile" 方法,将加载的数据写入应用程序的 Documents 目录中的文件中。如果您需要进一步的帮助,请告诉我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 2014-01-18
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多