Как загрузить файлы из UIWebView и открыть снова - PullRequest
14 голосов
/ 11 сентября 2011

Как создать «менеджер загрузок», который бы определял, когда ссылка, по которой вы нажимаете (в 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 для лучшего понимания того, что я пытаюсь сделать.

Каков наилучший способ сделать это?

1 Ответ

31 голосов
/ 11 сентября 2011

Используйте метод - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType в делегате вашего UiWebView, чтобы определить, когда он хочет загрузить ресурс.

Когда вызывается метод get, вам просто нужно проанализировать URL-адрес из параметра (NSURLRequest *)request и вернуть 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_: I 'обновили пример кода после нашего обсуждения ваших проблем в чате:

- (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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...