识别UIWebView文件类型

时间:2011-04-11 10:31:53

标签: objective-c pdf uiwebview uiwebviewdelegate

我希望检测何时单击PDF并将其显示在单独的UIWebView中。这就是我目前所拥有的:

- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {
    NSURL *url = [request URL];
    NSString *urlString = [url absoluteString];
    if (fileType != @"PDF") {

        if([urlString rangeOfString:@".pdf"].location == NSNotFound){
            return true;
        } else {
            NSURL *filePath = [NSURL URLWithString:urlString];
            NSURLRequest *requestObj = [NSURLRequest requestWithURL:filePath];
            [pdfViewer loadRequest:requestObj];
            [self.view addSubview:topView];

            fileType = @"PDF";

            return false;
        }
    } else {
        return true;
    }   
}

这很好用。然而它确实有一个耀眼的缺陷:

“http://www.example.com/ikb3987basd”

怎么样?

如何识别没有扩展名的文件类型?是否有关于我可以检查的文件的某种数据?

3 个答案:

答案 0 :(得分:1)

在将请求发送到服务器之前,您无法知道响应的内容类型。此时,客户端无法知道隐藏在某个URL后面的内容。只有当客户端收到服务器的响应时,才能检查HTTP头中的Content-Type字段。

我相信使用公共UIWebView API无法实现您想要实现的目标(除非您首先启动独立连接以检索URL的标头并检查响应的Content-Type)。

答案 1 :(得分:0)

使用狭义相对论,你可以证明当你甚至没有文件时就不可能知道文件......:p

此外,我不会分析“pdf”的整个网址,而只会查看您可以从中获取的文件扩展名

[[url absoluteString] pathExtension]

答案 2 :(得分:0)

您可以使用NSURLProtocol sublcass来捕获由UIWebView生成的所有请求和响应(但不是(!)WKWebView)。

AppDelegate中的...didFinishLaunchingWithOptions

[NSURLProtocol registerClass:[MyCustomProtocol class]];

这将强制MyCustomProtocol处理所有网络请求。

实现MyCustomProtocol之类的(代码未测试):

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    return YES;
}

+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request{
    return request;
}

- (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id<NSURLProtocolClient>)client
{
    self = [super initWithRequest:request cachedResponse:cachedResponse client:client];
    if (self) {
         return self;
    }
    return nil;
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // parse response here for mime-type and content-disposition
    if (shouldDownload) {
        // handle downloading response.URL
        completionHandler(NSURLSessionResponseBecomeDownload);
    } else {
        completionHandler(NSURLSessionResponseAllow);
    }
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];

}

您可以在Apple NSURLProtocolexample

中找到有关here的更多详细信息
相关问题