来自UIWebVIew的带有外部应用程序的iOS Open Document

时间:2015-02-02 14:02:45

标签: ios uiwebview external document

我有UIWebView。当单击包含文档的链接时,我想在外部应用程序(办公室,openoffice等)中打开该文档,但不要在UIWebView内打开。

我知道如何为电子邮件做这件事:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[[request URL] scheme] isEqual:@"mailto"]) {
    [[UIApplication sharedApplication] openURL:[request URL]];
    return NO;
}
return YES;

}

有没有办法做到这一点,但文件? 谢谢!

修改 这就是我所做的:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL* possibleDocumentURL = [request mainDocumentURL];
    NSString* extension = [[possibleDocumentURL lastPathComponent] pathExtension];

    if ([[[request URL] scheme] isEqual:@"mailto"]) {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;

    }else if ([extension isEqualToString:@"pdf"] || [extension isEqualToString:@"docx"]){

        NSURLRequest *req = [[NSURLRequest alloc] initWithURL:possibleDocumentURL];
        [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse
*resp, NSData *respData, NSError *error){ stringByAppendingString:names[names.count-1]];
        NSString *fileName = @"myFile";
        NSString * path = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
        NSError *errorC = nil;
        BOOL success = [respData writeToFile:path
                                         options:NSDataWritingFileProtectionComplete
                                           error:&errorC];

        if (success) {
            self.documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path]];
             self.documentController.delegate = self;
             [self.documentController presentOptionsMenuFromRect:CGRectZero inView:self.view animated:YES];
         } else {
             NSLog(@"fail: %@", errorC.description);
         }
    }];

        return NO;
   }

   return YES; 
}

现在的问题是UIDocumentInteractionController仅显示MailMessages个应用。我需要用于打开pdfdocx等文件的应用。

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:4)

UIDocumentInteractionController将为您效劳。

Apple docs

Great step by step tutorial

答案 1 :(得分:2)

[UIWebViewDelegate webView: shouldStartLoadWithRequest: navigationType: navigationType:]中,您可以检查网址是否与文档相符。最简单的方法就是寻找pdf,doc等。如果你想要它更好,那么使用UTTypes。

NSURL* possibleDocumentURL = [request mainDocumentURL];
NSString* extension = [[possibleDocumentURL lastPathComponent] pathExtension];
// TODO: check ending

如果它是文档的URL,则只需下载文档即可。您现在可以打开DocumentPreviewControllerUIDocumentInteractionControllerQLPreviewController。用户仍然需要选择文件的位置。

如果要打开的应用程序支持自定义URL方案,您可以直接将URL或文件本身传递给它,而无需用户交互。