UIWebView - 使用自定义内容类型加载网址

时间:2014-01-10 13:17:17

标签: ios uiwebview

在我的应用程序中,我使用Web视图(简单的UIWebView)来显示列出一些文件的网页。 出于某种原因,服务器(不在我的控制范围内)想要强制用户下载文件,据我所知,它以两种方式完成 - (a)设置Content-Disposition:attachment;在标题中和(b)将内容类型更改为Content-Type:application / x-forcedownload。

当尝试在Web视图中打开其中一个文件时,Web视图将显示已知的“Frame load interrupted”错误,如果在手机的本机Safari应用程序中访问同一页面并单击其中一个文件,它将会显示显示不同的错误,说“下载失败 - Safari无法下载此文件”。

在我看来,这些错误的原因是内容类型已更改,尽管该文件是一个常规,简单的PDF文件。

所以,如果我能告诉我的网页视图正确的内容类型(或者甚至忽略它,因为文件的扩展名是.pdf),我相信它会很高兴地显示该文件。

你是如何实现的?

非常感谢,

1 个答案:

答案 0 :(得分:2)

最后,我使用UIWebViewDelegate识别对此类文件的请求,在后台下载文件内容并使用[webView loadData:self.webdata MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil]显示;

这是完成工作的代码(self.webdata是类的NSMutableData属性)。

- (BOOL)webView:(UIWebView *)_webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    // If the link is about to use a weird Content-Type, stop the UIWebView request
    //    and get the data through a NSUrlConnection
    if ([request.URL.absoluteString hasSuffix:@"forcedownload=1"])
    {
        [NSURLConnection connectionWithRequest:request delegate:self];
        // Show an activity indicator
        [self showActivityIndicators];
        return NO;
    }

    return [super webView:_webView shouldStartLoadWithRequest:request navigationType:navigationType];
}

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    self.webdata = [[NSMutableData alloc] init];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.webdata appendData:data];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
    [self hideActivityIndicators];

    // Loads an empty URL to give the user the "Back" button ability
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
    // Load the content
    [webView loadData:self.webdata MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil];
}